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,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/SolutionCrawler/IncrementalAnalyzerProviderMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class IncrementalAnalyzerProviderMetadata : WorkspaceKindMetadata { public bool HighPriorityForActiveFile { get; } public string Name { get; } public IncrementalAnalyzerProviderMetadata(IDictionary<string, object> data) : base(data) { this.HighPriorityForActiveFile = (bool)data.GetValueOrDefault("HighPriorityForActiveFile"); this.Name = (string)data.GetValueOrDefault("Name"); } public IncrementalAnalyzerProviderMetadata(string name, bool highPriorityForActiveFile, params string[] workspaceKinds) : base(workspaceKinds) { this.HighPriorityForActiveFile = highPriorityForActiveFile; this.Name = name; } public override bool Equals(object obj) { return obj is IncrementalAnalyzerProviderMetadata metadata && base.Equals(obj) && HighPriorityForActiveFile == metadata.HighPriorityForActiveFile && Name == metadata.Name; } public override int GetHashCode() { var hashCode = 1997033996; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + HighPriorityForActiveFile.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); return hashCode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class IncrementalAnalyzerProviderMetadata : WorkspaceKindMetadata { public bool HighPriorityForActiveFile { get; } public string Name { get; } public IncrementalAnalyzerProviderMetadata(IDictionary<string, object> data) : base(data) { this.HighPriorityForActiveFile = (bool)data.GetValueOrDefault("HighPriorityForActiveFile"); this.Name = (string)data.GetValueOrDefault("Name"); } public IncrementalAnalyzerProviderMetadata(string name, bool highPriorityForActiveFile, params string[] workspaceKinds) : base(workspaceKinds) { this.HighPriorityForActiveFile = highPriorityForActiveFile; this.Name = name; } public override bool Equals(object obj) { return obj is IncrementalAnalyzerProviderMetadata metadata && base.Equals(obj) && HighPriorityForActiveFile == metadata.HighPriorityForActiveFile && Name == metadata.Name; } public override int GetHashCode() { var hashCode = 1997033996; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + HighPriorityForActiveFile.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); return hashCode; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignatureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [WorkItem(8333, "https://github.com/dotnet/roslyn/issues/8333")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInExpressionBody() { var markup = @" class Ext { void Goo(int a, int b) => [||]0; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(1905, "https://github.com/dotnet/roslyn/issues/1905")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCommand() { var markup = @" class Program { static void Main(string[] args) { M1(1, 2);$$ M2(1, 2, 3); } static void M1(int x, int y) { } static void M2(int x, int y, int z) { } }"; var expectedCode = @" class Program { static void Main(string[] args) { M1(2, 1); M2(1, 2, 3); } static void M1(int y, int x) { } static void M2(int x, int y, int z) { } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup: markup, updatedSignature: new[] { 1, 0 }, expectedUpdatedInvocationDocumentCode: expectedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnLambdaWithTwoDiscardParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = $$(int _, string _) => 1; } }"; var expectedCode = @" class Program { static void M() { System.Func<int, string, int> f = (string _, int _) => 1; } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup: markup, updatedSignature: new[] { 1, 0 }, expectedUpdatedInvocationDocumentCode: expectedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnAnonymousMethodWithTwoParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = [||]delegate(int x, string y) { return 1; }; } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnAnonymousMethodWithTwoDiscardParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = [||]delegate(int _, string _) { return 1; }; } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCodeAction() { var markup = @" class Program { static void Main(string[] args) { M1(1, 2);[||] M2(1, 2, 3); } static void M1(int x, int y) { } static void M2(int x, int y, int z) { } }"; await TestMissingAsync(markup); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingWhitespace() { var markup = @" class Ext { [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingTrivia() { var markup = @" class Ext { // [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingTrivia2() { var markup = @" class Ext { [||]// void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingDocComment() { var markup = @" class Ext { /// [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingDocComment2() { var markup = @" class Ext { [||]/// void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes1() { var markup = @" class Ext { [||][X] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes2() { var markup = @" class Ext { [[||]X] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes3() { var markup = @" class Ext { [X][||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInConstraints() { var markup = @" class Ext { void Goo<T>(int a, int b) where [||]T : class { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: 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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [WorkItem(8333, "https://github.com/dotnet/roslyn/issues/8333")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInExpressionBody() { var markup = @" class Ext { void Goo(int a, int b) => [||]0; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(1905, "https://github.com/dotnet/roslyn/issues/1905")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCommand() { var markup = @" class Program { static void Main(string[] args) { M1(1, 2);$$ M2(1, 2, 3); } static void M1(int x, int y) { } static void M2(int x, int y, int z) { } }"; var expectedCode = @" class Program { static void Main(string[] args) { M1(2, 1); M2(1, 2, 3); } static void M1(int y, int x) { } static void M2(int x, int y, int z) { } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup: markup, updatedSignature: new[] { 1, 0 }, expectedUpdatedInvocationDocumentCode: expectedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnLambdaWithTwoDiscardParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = $$(int _, string _) => 1; } }"; var expectedCode = @" class Program { static void M() { System.Func<int, string, int> f = (string _, int _) => 1; } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup: markup, updatedSignature: new[] { 1, 0 }, expectedUpdatedInvocationDocumentCode: expectedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnAnonymousMethodWithTwoParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = [||]delegate(int x, string y) { return 1; }; } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestOnAnonymousMethodWithTwoDiscardParameters_ViaCommand() { var markup = @" class Program { static void M() { System.Func<int, string, int> f = [||]delegate(int _, string _) { return 1; }; } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestAfterSemicolonForInvocationInExpressionStatement_ViaCodeAction() { var markup = @" class Program { static void Main(string[] args) { M1(1, 2);[||] M2(1, 2, 3); } static void M1(int x, int y) { } static void M2(int x, int y, int z) { } }"; await TestMissingAsync(markup); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingWhitespace() { var markup = @" class Ext { [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingTrivia() { var markup = @" class Ext { // [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingTrivia2() { var markup = @" class Ext { [||]// void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingDocComment() { var markup = @" class Ext { /// [||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingDocComment2() { var markup = @" class Ext { [||]/// void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes1() { var markup = @" class Ext { [||][X] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes2() { var markup = @" class Ext { [[||]X] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInLeadingAttributes3() { var markup = @" class Ext { [X][||] void Goo(int a, int b) { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WorkItem(17309, "https://github.com/dotnet/roslyn/issues/17309")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task TestNotInConstraints() { var markup = @" class Ext { void Goo<T>(int a, int b) where [||]T : class { }; }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A context for binding type parameter symbols of named types. /// </summary> internal sealed class TypeParameterBuilder { private readonly SyntaxReference _syntaxRef; private readonly SourceNamedTypeSymbol _owner; private readonly Location _location; internal TypeParameterBuilder(SyntaxReference syntaxRef, SourceNamedTypeSymbol owner, Location location) { _syntaxRef = syntaxRef; Debug.Assert(syntaxRef.GetSyntax().IsKind(SyntaxKind.TypeParameter)); _owner = owner; _location = location; } internal TypeParameterSymbol MakeSymbol(int ordinal, IList<TypeParameterBuilder> builders, BindingDiagnosticBag diagnostics) { var syntaxNode = (TypeParameterSyntax)_syntaxRef.GetSyntax(); var result = new SourceTypeParameterSymbol( _owner, syntaxNode.Identifier.ValueText, ordinal, syntaxNode.VarianceKeyword.VarianceKindFromToken(), ToLocations(builders), ToSyntaxRefs(builders)); // SPEC: A type parameter [of a type] cannot have the same name as the type itself. if (result.Name == result.ContainingSymbol.Name) { diagnostics.Add(ErrorCode.ERR_TypeVariableSameAsParent, result.Locations[0], result.Name); } return result; } private static ImmutableArray<Location> ToLocations(IList<TypeParameterBuilder> builders) { var arrayBuilder = ArrayBuilder<Location>.GetInstance(builders.Count); foreach (var builder in builders) { arrayBuilder.Add(builder._location); } return arrayBuilder.ToImmutableAndFree(); } private static ImmutableArray<SyntaxReference> ToSyntaxRefs(IList<TypeParameterBuilder> builders) { var arrayBuilder = ArrayBuilder<SyntaxReference>.GetInstance(builders.Count); foreach (var builder in builders) { arrayBuilder.Add(builder._syntaxRef); } return arrayBuilder.ToImmutableAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A context for binding type parameter symbols of named types. /// </summary> internal sealed class TypeParameterBuilder { private readonly SyntaxReference _syntaxRef; private readonly SourceNamedTypeSymbol _owner; private readonly Location _location; internal TypeParameterBuilder(SyntaxReference syntaxRef, SourceNamedTypeSymbol owner, Location location) { _syntaxRef = syntaxRef; Debug.Assert(syntaxRef.GetSyntax().IsKind(SyntaxKind.TypeParameter)); _owner = owner; _location = location; } internal TypeParameterSymbol MakeSymbol(int ordinal, IList<TypeParameterBuilder> builders, BindingDiagnosticBag diagnostics) { var syntaxNode = (TypeParameterSyntax)_syntaxRef.GetSyntax(); var result = new SourceTypeParameterSymbol( _owner, syntaxNode.Identifier.ValueText, ordinal, syntaxNode.VarianceKeyword.VarianceKindFromToken(), ToLocations(builders), ToSyntaxRefs(builders)); // SPEC: A type parameter [of a type] cannot have the same name as the type itself. if (result.Name == result.ContainingSymbol.Name) { diagnostics.Add(ErrorCode.ERR_TypeVariableSameAsParent, result.Locations[0], result.Name); } return result; } private static ImmutableArray<Location> ToLocations(IList<TypeParameterBuilder> builders) { var arrayBuilder = ArrayBuilder<Location>.GetInstance(builders.Count); foreach (var builder in builders) { arrayBuilder.Add(builder._location); } return arrayBuilder.ToImmutableAndFree(); } private static ImmutableArray<SyntaxReference> ToSyntaxRefs(IList<TypeParameterBuilder> builders) { var arrayBuilder = ArrayBuilder<SyntaxReference>.GetInstance(builders.Count); foreach (var builder in builders) { arrayBuilder.Add(builder._syntaxRef); } return arrayBuilder.ToImmutableAndFree(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/SolutionCrawler/State/AbstractAnalyzerState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler.State { internal abstract class AbstractAnalyzerState<TKey, TValue, TData> { protected readonly ConcurrentDictionary<TKey, CacheEntry> DataCache = new(concurrencyLevel: 2, capacity: 10); protected abstract TKey GetCacheKey(TValue value); protected abstract Solution GetSolution(TValue value); protected abstract bool ShouldCache(TValue value); protected abstract int GetCount(TData data); protected abstract Task<Stream> ReadStreamAsync(IPersistentStorage storage, TValue value, CancellationToken cancellationToken); protected abstract TData TryGetExistingData(Stream stream, TValue value, CancellationToken cancellationToken); protected abstract void WriteTo(Stream stream, TData data, CancellationToken cancellationToken); protected abstract Task<bool> WriteStreamAsync(IPersistentStorage storage, TValue value, Stream stream, CancellationToken cancellationToken); public int Count => DataCache.Count; public int GetDataCount(TKey key) { if (!DataCache.TryGetValue(key, out var entry)) { return 0; } return entry.Count; } public async Task<TData> TryGetExistingDataAsync(TValue value, CancellationToken cancellationToken) { if (!DataCache.TryGetValue(GetCacheKey(value), out var entry)) { // we don't have data return default; } // we have in memory cache for the document if (entry.HasCachedData) { return entry.Data; } // we have persisted data var solution = GetSolution(value); var persistService = solution.Workspace.Services.GetService<IPersistentStorageService>(); try { var storage = await persistService.GetStorageAsync(solution, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = await ReadStreamAsync(storage, value, cancellationToken).ConfigureAwait(false); if (stream != null) { return TryGetExistingData(stream, value, cancellationToken); } } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { } return default; } public async Task PersistAsync(TValue value, TData data, CancellationToken cancellationToken) { var succeeded = await WriteToStreamAsync(value, data, cancellationToken).ConfigureAwait(false); var id = GetCacheKey(value); // if data is for opened document or if persistence failed, // we keep small cache so that we don't pay cost of deserialize/serializing data that keep changing DataCache[id] = (!succeeded || ShouldCache(value)) ? new CacheEntry(data, GetCount(data)) : new CacheEntry(default, GetCount(data)); } public virtual bool Remove(TKey id) { // remove doesn't actually remove data from the persistent storage // that will be automatically managed by the service itself. return DataCache.TryRemove(id, out _); } private async Task<bool> WriteToStreamAsync(TValue value, TData data, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); WriteTo(stream, data, cancellationToken); var solution = GetSolution(value); var persistService = solution.Workspace.Services.GetService<IPersistentStorageService>(); var storage = await persistService.GetStorageAsync(solution, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); stream.Position = 0; return await WriteStreamAsync(storage, value, stream, cancellationToken).ConfigureAwait(false); } protected readonly struct CacheEntry { public readonly TData Data; public readonly int Count; public CacheEntry(TData data, int count) { Data = data; Count = count; } public bool HasCachedData => !object.Equals(Data, 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.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler.State { internal abstract class AbstractAnalyzerState<TKey, TValue, TData> { protected readonly ConcurrentDictionary<TKey, CacheEntry> DataCache = new(concurrencyLevel: 2, capacity: 10); protected abstract TKey GetCacheKey(TValue value); protected abstract Solution GetSolution(TValue value); protected abstract bool ShouldCache(TValue value); protected abstract int GetCount(TData data); protected abstract Task<Stream> ReadStreamAsync(IPersistentStorage storage, TValue value, CancellationToken cancellationToken); protected abstract TData TryGetExistingData(Stream stream, TValue value, CancellationToken cancellationToken); protected abstract void WriteTo(Stream stream, TData data, CancellationToken cancellationToken); protected abstract Task<bool> WriteStreamAsync(IPersistentStorage storage, TValue value, Stream stream, CancellationToken cancellationToken); public int Count => DataCache.Count; public int GetDataCount(TKey key) { if (!DataCache.TryGetValue(key, out var entry)) { return 0; } return entry.Count; } public async Task<TData> TryGetExistingDataAsync(TValue value, CancellationToken cancellationToken) { if (!DataCache.TryGetValue(GetCacheKey(value), out var entry)) { // we don't have data return default; } // we have in memory cache for the document if (entry.HasCachedData) { return entry.Data; } // we have persisted data var solution = GetSolution(value); var persistService = solution.Workspace.Services.GetService<IPersistentStorageService>(); try { var storage = await persistService.GetStorageAsync(solution, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = await ReadStreamAsync(storage, value, cancellationToken).ConfigureAwait(false); if (stream != null) { return TryGetExistingData(stream, value, cancellationToken); } } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { } return default; } public async Task PersistAsync(TValue value, TData data, CancellationToken cancellationToken) { var succeeded = await WriteToStreamAsync(value, data, cancellationToken).ConfigureAwait(false); var id = GetCacheKey(value); // if data is for opened document or if persistence failed, // we keep small cache so that we don't pay cost of deserialize/serializing data that keep changing DataCache[id] = (!succeeded || ShouldCache(value)) ? new CacheEntry(data, GetCount(data)) : new CacheEntry(default, GetCount(data)); } public virtual bool Remove(TKey id) { // remove doesn't actually remove data from the persistent storage // that will be automatically managed by the service itself. return DataCache.TryRemove(id, out _); } private async Task<bool> WriteToStreamAsync(TValue value, TData data, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); WriteTo(stream, data, cancellationToken); var solution = GetSolution(value); var persistService = solution.Workspace.Services.GetService<IPersistentStorageService>(); var storage = await persistService.GetStorageAsync(solution, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); stream.Position = 0; return await WriteStreamAsync(storage, value, stream, cancellationToken).ConfigureAwait(false); } protected readonly struct CacheEntry { public readonly TData Data; public readonly int Count; public CacheEntry(TData data, int count) { Data = data; Count = count; } public bool HasCachedData => !object.Equals(Data, null); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractToMethodConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Method() like query.ToList(), query.Count(). /// </summary> internal abstract class AbstractToMethodConverter : AbstractConverter { // It is "item" for for "list.Add(item)" // It can be anything for "counter++". It will be ingored in the case. private readonly ExpressionSyntax _selectExpression; // It is "list" for "list.Add(item)" // It is "counter" for "counter++" private readonly ExpressionSyntax _modifyingExpression; // Trivia around "counter++;" or "list.Add(item);". Required to keep comments. private readonly SyntaxTrivia[] _trivia; public AbstractToMethodConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo) { _selectExpression = selectExpression; _modifyingExpression = modifyingExpression; _trivia = trivia; } protected abstract string MethodName { get; } protected abstract bool CanReplaceInitialization(ExpressionSyntax expressionSyntax, CancellationToken cancellationToken); protected abstract StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression); public override void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken) { var queryOrLinqInvocationExpression = CreateQueryExpressionOrLinqInvocation( _selectExpression, Enumerable.Empty<SyntaxToken>(), Enumerable.Empty<SyntaxToken>(), convertToQuery); var previous = ForEachInfo.ForEachStatement.GetPreviousStatement(); if (previous != null && !previous.ContainsDirectives) { switch (previous.Kind()) { case SyntaxKind.LocalDeclarationStatement: var variables = ((LocalDeclarationStatementSyntax)previous).Declaration.Variables; var lastDeclaration = variables.Last(); // Check if // var ...., list = new List<T>(); or var ..., counter = 0; // is just before the foreach. // If so, join the declaration with the query. if (_modifyingExpression is IdentifierNameSyntax identifierName && lastDeclaration.Identifier.ValueText.Equals(identifierName.Identifier.ValueText) && CanReplaceInitialization(lastDeclaration.Initializer.Value, cancellationToken)) { Convert(lastDeclaration.Initializer.Value, variables.Count == 1 ? (SyntaxNode)previous : lastDeclaration); return; } break; case SyntaxKind.ExpressionStatement: // Check if // list = new List<T>(); or counter = 0; // is just before the foreach. // If so, join the assignment with the query. if (((ExpressionStatementSyntax)previous).Expression is AssignmentExpressionSyntax assignmentExpression && SymbolEquivalenceComparer.Instance.Equals( ForEachInfo.SemanticModel.GetSymbolInfo(assignmentExpression.Left, cancellationToken).Symbol, ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol) && CanReplaceInitialization(assignmentExpression.Right, cancellationToken)) { Convert(assignmentExpression.Right, previous); return; } break; } } // At least, we already can convert to // list.AddRange(query) or counter += query.Count(); editor.ReplaceNode( ForEachInfo.ForEachStatement, CreateDefaultStatement(queryOrLinqInvocationExpression, _modifyingExpression).WithAdditionalAnnotations(Formatter.Annotation)); return; void Convert(ExpressionSyntax replacingExpression, SyntaxNode nodeToRemoveIfFollowedByReturn) { SyntaxTrivia[] leadingTrivia; // Check if expressionAssigning is followed by a return statement. var expresisonSymbol = ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol; if (expresisonSymbol is ILocalSymbol && ForEachInfo.ForEachStatement.GetNextStatement() is ReturnStatementSyntax returnStatement && !returnStatement.ContainsDirectives && SymbolEquivalenceComparer.Instance.Equals( expresisonSymbol, ForEachInfo.SemanticModel.GetSymbolInfo(returnStatement.Expression, cancellationToken).Symbol)) { // Input: // var list = new List<T>(); or var counter = 0; // foreach(...) // { // ... // ... // list.Add(item); or counter++; // } // return list; or return counter; // // Output: // return queryGenerated.ToList(); or return queryGenerated.Count(); replacingExpression = returnStatement.Expression; leadingTrivia = GetTriviaFromNode(nodeToRemoveIfFollowedByReturn) .Concat(SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression)).ToArray(); editor.RemoveNode(nodeToRemoveIfFollowedByReturn); } else { leadingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression); } editor.ReplaceNode( replacingExpression, CreateInvocationExpression(queryOrLinqInvocationExpression) .WithCommentsFrom(leadingTrivia, _trivia).KeepCommentsAndAddElasticMarkers()); editor.RemoveNode(ForEachInfo.ForEachStatement); } static SyntaxTrivia[] GetTriviaFromVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => SyntaxNodeOrTokenExtensions.GetTrivia(variableDeclarator.Identifier, variableDeclarator.Initializer.EqualsToken, variableDeclarator.Initializer.Value); static SyntaxTrivia[] GetTriviaFromNode(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: var localDeclaration = (LocalDeclarationStatementSyntax)node; if (localDeclaration.Declaration.Variables.Count != 1) { throw ExceptionUtilities.Unreachable; } return new IEnumerable<SyntaxTrivia>[] { SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.Declaration.Type), GetTriviaFromVariableDeclarator(localDeclaration.Declaration.Variables[0]), SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.SemicolonToken)}.Flatten().ToArray(); case SyntaxKind.VariableDeclarator: return GetTriviaFromVariableDeclarator((VariableDeclaratorSyntax)node); case SyntaxKind.ExpressionStatement: if (((ExpressionStatementSyntax)node).Expression is AssignmentExpressionSyntax assignmentExpression) { return SyntaxNodeOrTokenExtensions.GetTrivia( assignmentExpression.Left, assignmentExpression.OperatorToken, assignmentExpression.Right); } break; } throw ExceptionUtilities.Unreachable; } } // query => query.Method() // like query.Count() or query.ToList() protected InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax queryOrLinqInvocationExpression) => SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParenthesizedExpression(queryOrLinqInvocationExpression), SyntaxFactory.IdentifierName(MethodName))).WithAdditionalAnnotations(Formatter.Annotation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Method() like query.ToList(), query.Count(). /// </summary> internal abstract class AbstractToMethodConverter : AbstractConverter { // It is "item" for for "list.Add(item)" // It can be anything for "counter++". It will be ingored in the case. private readonly ExpressionSyntax _selectExpression; // It is "list" for "list.Add(item)" // It is "counter" for "counter++" private readonly ExpressionSyntax _modifyingExpression; // Trivia around "counter++;" or "list.Add(item);". Required to keep comments. private readonly SyntaxTrivia[] _trivia; public AbstractToMethodConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo) { _selectExpression = selectExpression; _modifyingExpression = modifyingExpression; _trivia = trivia; } protected abstract string MethodName { get; } protected abstract bool CanReplaceInitialization(ExpressionSyntax expressionSyntax, CancellationToken cancellationToken); protected abstract StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression); public override void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken) { var queryOrLinqInvocationExpression = CreateQueryExpressionOrLinqInvocation( _selectExpression, Enumerable.Empty<SyntaxToken>(), Enumerable.Empty<SyntaxToken>(), convertToQuery); var previous = ForEachInfo.ForEachStatement.GetPreviousStatement(); if (previous != null && !previous.ContainsDirectives) { switch (previous.Kind()) { case SyntaxKind.LocalDeclarationStatement: var variables = ((LocalDeclarationStatementSyntax)previous).Declaration.Variables; var lastDeclaration = variables.Last(); // Check if // var ...., list = new List<T>(); or var ..., counter = 0; // is just before the foreach. // If so, join the declaration with the query. if (_modifyingExpression is IdentifierNameSyntax identifierName && lastDeclaration.Identifier.ValueText.Equals(identifierName.Identifier.ValueText) && CanReplaceInitialization(lastDeclaration.Initializer.Value, cancellationToken)) { Convert(lastDeclaration.Initializer.Value, variables.Count == 1 ? (SyntaxNode)previous : lastDeclaration); return; } break; case SyntaxKind.ExpressionStatement: // Check if // list = new List<T>(); or counter = 0; // is just before the foreach. // If so, join the assignment with the query. if (((ExpressionStatementSyntax)previous).Expression is AssignmentExpressionSyntax assignmentExpression && SymbolEquivalenceComparer.Instance.Equals( ForEachInfo.SemanticModel.GetSymbolInfo(assignmentExpression.Left, cancellationToken).Symbol, ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol) && CanReplaceInitialization(assignmentExpression.Right, cancellationToken)) { Convert(assignmentExpression.Right, previous); return; } break; } } // At least, we already can convert to // list.AddRange(query) or counter += query.Count(); editor.ReplaceNode( ForEachInfo.ForEachStatement, CreateDefaultStatement(queryOrLinqInvocationExpression, _modifyingExpression).WithAdditionalAnnotations(Formatter.Annotation)); return; void Convert(ExpressionSyntax replacingExpression, SyntaxNode nodeToRemoveIfFollowedByReturn) { SyntaxTrivia[] leadingTrivia; // Check if expressionAssigning is followed by a return statement. var expresisonSymbol = ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol; if (expresisonSymbol is ILocalSymbol && ForEachInfo.ForEachStatement.GetNextStatement() is ReturnStatementSyntax returnStatement && !returnStatement.ContainsDirectives && SymbolEquivalenceComparer.Instance.Equals( expresisonSymbol, ForEachInfo.SemanticModel.GetSymbolInfo(returnStatement.Expression, cancellationToken).Symbol)) { // Input: // var list = new List<T>(); or var counter = 0; // foreach(...) // { // ... // ... // list.Add(item); or counter++; // } // return list; or return counter; // // Output: // return queryGenerated.ToList(); or return queryGenerated.Count(); replacingExpression = returnStatement.Expression; leadingTrivia = GetTriviaFromNode(nodeToRemoveIfFollowedByReturn) .Concat(SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression)).ToArray(); editor.RemoveNode(nodeToRemoveIfFollowedByReturn); } else { leadingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression); } editor.ReplaceNode( replacingExpression, CreateInvocationExpression(queryOrLinqInvocationExpression) .WithCommentsFrom(leadingTrivia, _trivia).KeepCommentsAndAddElasticMarkers()); editor.RemoveNode(ForEachInfo.ForEachStatement); } static SyntaxTrivia[] GetTriviaFromVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => SyntaxNodeOrTokenExtensions.GetTrivia(variableDeclarator.Identifier, variableDeclarator.Initializer.EqualsToken, variableDeclarator.Initializer.Value); static SyntaxTrivia[] GetTriviaFromNode(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: var localDeclaration = (LocalDeclarationStatementSyntax)node; if (localDeclaration.Declaration.Variables.Count != 1) { throw ExceptionUtilities.Unreachable; } return new IEnumerable<SyntaxTrivia>[] { SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.Declaration.Type), GetTriviaFromVariableDeclarator(localDeclaration.Declaration.Variables[0]), SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.SemicolonToken)}.Flatten().ToArray(); case SyntaxKind.VariableDeclarator: return GetTriviaFromVariableDeclarator((VariableDeclaratorSyntax)node); case SyntaxKind.ExpressionStatement: if (((ExpressionStatementSyntax)node).Expression is AssignmentExpressionSyntax assignmentExpression) { return SyntaxNodeOrTokenExtensions.GetTrivia( assignmentExpression.Left, assignmentExpression.OperatorToken, assignmentExpression.Right); } break; } throw ExceptionUtilities.Unreachable; } } // query => query.Method() // like query.Count() or query.ToList() protected InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax queryOrLinqInvocationExpression) => SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParenthesizedExpression(queryOrLinqInvocationExpression), SyntaxFactory.IdentifierName(MethodName))).WithAdditionalAnnotations(Formatter.Annotation); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/Organizing/Organizers/InterfaceDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class InterfaceDeclarationOrganizer : AbstractSyntaxNodeOrganizer<InterfaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InterfaceDeclarationOrganizer() { } protected override InterfaceDeclarationSyntax Organize( InterfaceDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Keyword, syntax.Identifier, syntax.TypeParameterList, syntax.BaseList, syntax.ConstraintClauses, syntax.OpenBraceToken, MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken), syntax.CloseBraceToken, syntax.SemicolonToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class InterfaceDeclarationOrganizer : AbstractSyntaxNodeOrganizer<InterfaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InterfaceDeclarationOrganizer() { } protected override InterfaceDeclarationSyntax Organize( InterfaceDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Keyword, syntax.Identifier, syntax.TypeParameterList, syntax.BaseList, syntax.ConstraintClauses, syntax.OpenBraceToken, MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken), syntax.CloseBraceToken, syntax.SemicolonToken); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests_LateBound.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SemanticModelGetSemanticInfoTests_LateBound : SemanticModelTestBase { [Fact] public void ObjectCreation() { string sourceCode = @" class C { public C(string x) {} public C(int x) {} public C(double x) {} public void M(dynamic d) { /*<bind>*/new C(d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectCreation_ByRefDynamicArgument1() { string sourceCode = @" class C { public C(out dynamic x, ref dynamic y) { } public void M(dynamic d) { /*<bind>*/new C(out d, ref d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Equal("C..ctor(out dynamic x, ref dynamic y)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } [Fact] public void ObjectCreation_ByRefDynamicArgument2() { string sourceCode = @" class C { public C(out dynamic x, dynamic y) {} public void M(dynamic d) { /*<bind>*/new C(out d, d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Equal("C..ctor(out dynamic x, dynamic y)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateInvocation() { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/d()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_DynamicReceiver() { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/ d.bar() /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_StaticReceiver() { string sourceCode = @" class C { public void M() { dynamic d = null; C s = null; /*<bind>*/ s.bar(d) /*</bind>*/; } public void bar(int a) { } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C.bar(System.Int32 a)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_TypeReceiver() { string sourceCode = @" class C { public static C Create(int arg) { return null; } public void M(dynamic d) { /*<bind>*/C.Create(d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.Equal("C C.Create(System.Int32 arg)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroup_EarlyBound() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(int x, string y) { /*<bind>*/Add/*</bind>*/(x); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.Null(semanticInfo.Type); Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroup_DynamicArg() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(dynamic x, string y) { /*<bind>*/Add/*</bind>*/(x); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.Null(semanticInfo.Type); // there is only one applicable candidate: Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_DynamicArg() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(dynamic x, string y) { /*<bind>*/Add(x)/*</bind>*/; } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.True(semanticInfo.Type.IsDynamic()); // there is only one applicable candidate: Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_StaticReceiver_ByRefDynamicArgument() { string sourceCode = @" class C { public void M() { dynamic d = null; C s = null; /*<bind>*/ s.bar(ref d) /*</bind>*/; } public int bar(ref dynamic a) { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.bar(ref dynamic a)", semanticInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(531141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531141")] public void MethodInvocation_StaticReceiver_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Dynamic { class FunctionTestingWithOverloading { public dynamic OverloadedFunction(dynamic d) { return d; } } class Program { static void Main(string[] args) { FunctionTestingWithOverloading obj = new FunctionTestingWithOverloading(); dynamic valueToBePassed = ""Hello""; dynamic result = obj./*<bind>*/OverloadedFunction/*</bind>*/(valueToBePassed); Console.WriteLine(""Value from overloaded function is {0}"", result); } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("dynamic Dynamic.FunctionTestingWithOverloading.OverloadedFunction(dynamic d)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("dynamic Dynamic.FunctionTestingWithOverloading.OverloadedFunction(dynamic d)", semanticInfo.MethodGroup.First().ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer() { string sourceCode = @" class C { public void M() { dynamic d = 0; var l = new List<int> { /*<bind>*/{ d }/*</bind>*/ }; } public void bar(int a) { } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); } [Fact] public void ObjectInitializer() { string sourceCode = @" class C { public dynamic Z; public void M() { dynamic d = 0; var c = new C { /*<bind>*/Z = d/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); // TODO: what about object initializers? } [Fact] public void Indexer_StaticReceiver() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; C c = null; var x = /*<bind>*/c[d]/*</bind>*/; } public int this[int a] { get { return 0; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("System.Int32 C.this[System.Int32 a] { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Indexer_DynamicReceiver() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; C c = null; var x = /*<bind>*/d[c]/*</bind>*/; } public int this[int a] { get { return 0; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MemberAccess() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x = /*<bind>*/d.F/*</bind>*/; } public int F { get; set; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnaryOperators() { var operators = new[] { "~", "!", "-", "+", "++", "--" }; var operatorNames = new[] { WellKnownMemberNames.OnesComplementOperatorName, WellKnownMemberNames.LogicalNotOperatorName, WellKnownMemberNames.UnaryNegationOperatorName, WellKnownMemberNames.UnaryPlusOperatorName, WellKnownMemberNames.IncrementOperatorName, WellKnownMemberNames.DecrementOperatorName }; for (int i = 0; i < operators.Length; i++) { var op = operators[i]; string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic dynamic." + operatorNames[i] + "(dynamic value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void Await() { string sourceCode = @" class C { public async Task<dynamic> M() { dynamic d = null; var x1 = /*<bind>*/await d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BinaryOperators() { foreach (var op in new[] { "*", "/", "%", "+", "-", "<<", ">>", "<", ">", "<=", ">=", "!=", "==", "^", "&", "|", "&&", "||" }) { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); if (op == "&&" || op == "||") { Assert.Null(semanticInfo.Symbol); } else { Assert.Equal("dynamic.operator " + op + "(dynamic, dynamic)", semanticInfo.Symbol.ToString()); } Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void NullCoalescing() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d ?? d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); // not a late bound operation Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalExpression_DynamicCondition() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d ? d : d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalExpression_StaticCondition() { string sourceCode = @" class C { public void TestMeth() { bool s = true; dynamic d = null; var x1 = /*<bind>*/s ? d : d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CompoundAssignment() { foreach (var op in new[] { "+=", "%=", "+=", "-=", "<<=", ">>=", "^=", "&=", "|=" }) { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/d" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic.operator " + op.Substring(0, op.Length - 1) + "(dynamic, dynamic)", semanticInfo.Symbol.ToString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void EventOperators() { foreach (var op in new[] { "+=", "-=" }) { string sourceCode = @" class C { public event System.Action E; public void M() { dynamic d = null; /*<bind>*/E" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(op == "+=" ? "void C.E.add" : "void C.E.remove", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SemanticModelGetSemanticInfoTests_LateBound : SemanticModelTestBase { [Fact] public void ObjectCreation() { string sourceCode = @" class C { public C(string x) {} public C(int x) {} public C(double x) {} public void M(dynamic d) { /*<bind>*/new C(d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectCreation_ByRefDynamicArgument1() { string sourceCode = @" class C { public C(out dynamic x, ref dynamic y) { } public void M(dynamic d) { /*<bind>*/new C(out d, ref d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Equal("C..ctor(out dynamic x, ref dynamic y)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } [Fact] public void ObjectCreation_ByRefDynamicArgument2() { string sourceCode = @" class C { public C(out dynamic x, dynamic y) {} public void M(dynamic d) { /*<bind>*/new C(out d, d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.Name); Assert.Equal("C..ctor(out dynamic x, dynamic y)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateInvocation() { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/d()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_DynamicReceiver() { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/ d.bar() /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_StaticReceiver() { string sourceCode = @" class C { public void M() { dynamic d = null; C s = null; /*<bind>*/ s.bar(d) /*</bind>*/; } public void bar(int a) { } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C.bar(System.Int32 a)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_TypeReceiver() { string sourceCode = @" class C { public static C Create(int arg) { return null; } public void M(dynamic d) { /*<bind>*/C.Create(d);/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.Equal("C C.Create(System.Int32 arg)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroup_EarlyBound() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(int x, string y) { /*<bind>*/Add/*</bind>*/(x); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.Null(semanticInfo.Type); Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroup_DynamicArg() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(dynamic x, string y) { /*<bind>*/Add/*</bind>*/(x); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.Null(semanticInfo.Type); // there is only one applicable candidate: Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_DynamicArg() { string source = @" using System.Collections.Generic; class List : List<int> { public void Add(dynamic x, string y) { /*<bind>*/Add(x)/*</bind>*/; } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(source); Assert.True(semanticInfo.Type.IsDynamic()); // there is only one applicable candidate: Assert.Equal("void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodInvocation_StaticReceiver_ByRefDynamicArgument() { string sourceCode = @" class C { public void M() { dynamic d = null; C s = null; /*<bind>*/ s.bar(ref d) /*</bind>*/; } public int bar(ref dynamic a) { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.bar(ref dynamic a)", semanticInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(531141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531141")] public void MethodInvocation_StaticReceiver_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Dynamic { class FunctionTestingWithOverloading { public dynamic OverloadedFunction(dynamic d) { return d; } } class Program { static void Main(string[] args) { FunctionTestingWithOverloading obj = new FunctionTestingWithOverloading(); dynamic valueToBePassed = ""Hello""; dynamic result = obj./*<bind>*/OverloadedFunction/*</bind>*/(valueToBePassed); Console.WriteLine(""Value from overloaded function is {0}"", result); } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("dynamic Dynamic.FunctionTestingWithOverloading.OverloadedFunction(dynamic d)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("dynamic Dynamic.FunctionTestingWithOverloading.OverloadedFunction(dynamic d)", semanticInfo.MethodGroup.First().ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer() { string sourceCode = @" class C { public void M() { dynamic d = 0; var l = new List<int> { /*<bind>*/{ d }/*</bind>*/ }; } public void bar(int a) { } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); } [Fact] public void ObjectInitializer() { string sourceCode = @" class C { public dynamic Z; public void M() { dynamic d = 0; var c = new C { /*<bind>*/Z = d/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); // TODO: what about object initializers? } [Fact] public void Indexer_StaticReceiver() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; C c = null; var x = /*<bind>*/c[d]/*</bind>*/; } public int this[int a] { get { return 0; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("System.Int32 C.this[System.Int32 a] { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Indexer_DynamicReceiver() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; C c = null; var x = /*<bind>*/d[c]/*</bind>*/; } public int this[int a] { get { return 0; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MemberAccess() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x = /*<bind>*/d.F/*</bind>*/; } public int F { get; set; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnaryOperators() { var operators = new[] { "~", "!", "-", "+", "++", "--" }; var operatorNames = new[] { WellKnownMemberNames.OnesComplementOperatorName, WellKnownMemberNames.LogicalNotOperatorName, WellKnownMemberNames.UnaryNegationOperatorName, WellKnownMemberNames.UnaryPlusOperatorName, WellKnownMemberNames.IncrementOperatorName, WellKnownMemberNames.DecrementOperatorName }; for (int i = 0; i < operators.Length; i++) { var op = operators[i]; string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic dynamic." + operatorNames[i] + "(dynamic value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void Await() { string sourceCode = @" class C { public async Task<dynamic> M() { dynamic d = null; var x1 = /*<bind>*/await d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BinaryOperators() { foreach (var op in new[] { "*", "/", "%", "+", "-", "<<", ">>", "<", ">", "<=", ">=", "!=", "==", "^", "&", "|", "&&", "||" }) { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); if (op == "&&" || op == "||") { Assert.Null(semanticInfo.Symbol); } else { Assert.Equal("dynamic.operator " + op + "(dynamic, dynamic)", semanticInfo.Symbol.ToString()); } Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void NullCoalescing() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d ?? d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); // not a late bound operation Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalExpression_DynamicCondition() { string sourceCode = @" class C { public void TestMeth() { dynamic d = null; var x1 = /*<bind>*/d ? d : d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalExpression_StaticCondition() { string sourceCode = @" class C { public void TestMeth() { bool s = true; dynamic d = null; var x1 = /*<bind>*/s ? d : d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CompoundAssignment() { foreach (var op in new[] { "+=", "%=", "+=", "-=", "<<=", ">>=", "^=", "&=", "|=" }) { string sourceCode = @" class C { public void M() { dynamic d = null; /*<bind>*/d" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.True(semanticInfo.Type.IsDynamic()); Assert.True(semanticInfo.ConvertedType.IsDynamic()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic.operator " + op.Substring(0, op.Length - 1) + "(dynamic, dynamic)", semanticInfo.Symbol.ToString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void EventOperators() { foreach (var op in new[] { "+=", "-=" }) { string sourceCode = @" class C { public event System.Action E; public void M() { dynamic d = null; /*<bind>*/E" + op + @"d/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(op == "+=" ? "void C.E.add" : "void C.E.remove", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.LateBound, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenInParametersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenInParametersTests : CompilingTestBase { [Fact] public void ThreeParamReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { M(y: in GetField(0).X, z: GetField(1).X, x: GetField(2).X); } static void M(in int x, in int y, in int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }", expectedOutput: @"GetField 0 0 GetField 1 1 GetField 2 2 3 3 3"); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: stloc.1 IL_0018: ldc.i4.2 IL_0019: call ""ref C.S C.GetField(int)"" IL_001e: ldflda ""int C.S.X"" IL_0023: ldloc.0 IL_0024: ldloc.1 IL_0025: call ""void C.M(in int, in int, in int)"" IL_002a: ret }"); } [Fact] public void InParamReadonlyFieldReorder() { var comp = CompileAndVerify(@" using System; class C { private static readonly int _f = 0; public C() { M(y: _f, x: _f + 1); M(y: in _f, x: _f + 1); } public static void Main() { M(y: _f, x: _f + 1); M(y: in _f, x: _f + 1); _ = new C(); } static void M(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0 1 0 1 0 1 0", verify: Verification.Fails); comp.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 2 .locals init (int& V_0, int V_1) IL_0000: ldsflda ""int C._f"" IL_0005: stloc.0 IL_0006: ldsfld ""int C._f"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldloc.0 IL_0011: call ""void C.M(in int, in int)"" IL_0016: ldsflda ""int C._f"" IL_001b: stloc.0 IL_001c: ldsfld ""int C._f"" IL_0021: ldc.i4.1 IL_0022: add IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void C.M(in int, in int)"" IL_002c: newobj ""C..ctor()"" IL_0031: pop IL_0032: ret }"); } [Fact] public void InParamCallOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; M(in x); } static void M(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.0 IL_0005: call ""void C.M(in int, int)"" IL_000a: ret }"); } [Fact] public void InParamCtorOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; new C(in x); } public C(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 12 (0xc) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.0 IL_0005: newobj ""C..ctor(in int, int)"" IL_000a: pop IL_000b: ret }"); } [Fact] public void InParamInitializerOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static int _x = 1; public int _f = M(in _x); public static void Main() { new C(); } public static int M(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); return x; } }", expectedOutput: @"1 0"); comp.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldsflda ""int C._x"" IL_0006: ldc.i4.0 IL_0007: call ""int C.M(in int, int)"" IL_000c: stfld ""int C._f"" IL_0011: ldarg.0 IL_0012: call ""object..ctor()"" IL_0017: ret }"); } [Fact] public void InParamCollectionInitializerOptionalArg() { var comp = CompileAndVerify(@" using System; using System.Collections; class C : IEnumerable { public static void Main() { int x = 1; new C() { x }; } public IEnumerator GetEnumerator() => null; public void Add(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }"); comp.VerifyIL("C.Main", @" { // Code size 16 (0x10) .maxstack 3 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.0 IL_000a: callvirt ""void C.Add(in int, int)"" IL_000f: ret }"); } [Fact] public void InParamSetter() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C()[in _f] = 0; } public IEnumerator GetEnumerator() => null; public int this[in int x, int y = 0] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); } } }", expectedOutput: @"1 0 2"); comp.VerifyIL("C.Main", @" { // Code size 18 (0x12) .maxstack 4 IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: call ""void C.this[in int, int].set"" IL_0011: ret }"); } [Fact] public void InParamParamsArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; M(in x); } public static void M(in int x, params int[] p) { Console.WriteLine(x); Console.WriteLine(p.Length); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""int[] System.Array.Empty<int>()"" IL_0009: call ""void C.M(in int, params int[])"" IL_000e: ret }"); } [Fact] public void InParamReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { M(y: in GetField(0).X, x: GetField(1).X); } static void M(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 30 (0x1e) .maxstack 2 .locals init (int& V_0) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: ldloc.0 IL_0018: call ""void C.M(in int, in int)"" IL_001d: ret }"); } [Fact] public void InParamCtorReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { new C(y: in GetField(0).X, x: GetField(1).X); } public C(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (int& V_0) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: ldloc.0 IL_0018: newobj ""C..ctor(in int, in int)"" IL_001d: pop IL_001e: ret }"); } [Fact] public void InIndexerReorder() { var verifier = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { var c = new C(); _ = c[y: in GetField(0).X, x: in GetField(1).X]; } int this[in int x, in int y] { get { Console.WriteLine(x); Console.WriteLine(y); return x; } } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (int& V_0) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref C.S C.GetField(int)"" IL_000b: ldflda ""int C.S.X"" IL_0010: stloc.0 IL_0011: ldc.i4.1 IL_0012: call ""ref C.S C.GetField(int)"" IL_0017: ldflda ""int C.S.X"" IL_001c: ldloc.0 IL_001d: callvirt ""int C.this[in int, in int].get"" IL_0022: pop IL_0023: ret }"); } [Fact] public void InIndexerReorderWithCopy() { var verifier = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { var c = new C(); _ = c[y: GetField(0).X, x: GetField(1).X + 1]; _ = c[y: GetField(0).X + 2, x: GetField(1).X]; } int this[in int x, in int y] { get { Console.WriteLine(x); Console.WriteLine(y); return x; } } }", expectedOutput: @"GetField 0 0 GetField 1 1 3 2 GetField 2 0 GetField 3 1 4 5"); verifier.VerifyIL("C.Main", @" { // Code size 75 (0x4b) .maxstack 4 .locals init (int& V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: call ""ref C.S C.GetField(int)"" IL_000c: ldflda ""int C.S.X"" IL_0011: stloc.0 IL_0012: ldc.i4.1 IL_0013: call ""ref C.S C.GetField(int)"" IL_0018: ldfld ""int C.S.X"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: callvirt ""int C.this[in int, in int].get"" IL_0028: pop IL_0029: ldc.i4.0 IL_002a: call ""ref C.S C.GetField(int)"" IL_002f: ldfld ""int C.S.X"" IL_0034: ldc.i4.2 IL_0035: add IL_0036: stloc.1 IL_0037: ldc.i4.1 IL_0038: call ""ref C.S C.GetField(int)"" IL_003d: ldflda ""int C.S.X"" IL_0042: ldloca.s V_1 IL_0044: callvirt ""int C.this[in int, in int].get"" IL_0049: pop IL_004a: ret }"); } [Fact] public void InParamSetterReorder() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C()[y: in _f, x: _f] = 0; } public IEnumerator GetEnumerator() => null; public int this[in int x, in int y] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); Console.WriteLine(y); } } }", expectedOutput: @"1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 24 (0x18) .maxstack 4 .locals init (int& V_0) IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: stloc.0 IL_000b: ldsflda ""int C._f"" IL_0010: ldloc.0 IL_0011: ldc.i4.0 IL_0012: call ""void C.this[in int, in int].set"" IL_0017: ret }"); } [Fact] public void InParamMemberInitializerReorder() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C() { [y: in _f, x: _f] = 0 }; } public IEnumerator GetEnumerator() => null; public int this[in int x, in int y] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); Console.WriteLine(y); } } }", expectedOutput: @"1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 26 (0x1a) .maxstack 4 .locals init (int& V_0, int& V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: stloc.0 IL_000b: ldsflda ""int C._f"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: callvirt ""void C.this[in int, in int].set"" IL_0019: ret }"); } [Fact] public void RefReturnParamAccess() { var text = @" class Program { static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void InParamPassLValue() { var text = @" struct Program { public static void Main() { var local = 42; System.Console.WriteLine(M(local)); S1 s1 = default(S1); s1.X = 42; s1 += s1; System.Console.WriteLine(s1.X); } static ref readonly int M(in int x) { return ref x; } struct S1 { public int X; public static S1 operator +(in S1 x, in S1 y) { return new S1(){X = x.X + y.X}; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"42 84"); comp.VerifyIL("Program.Main()", @" { // Code size 55 (0x37) .maxstack 2 .locals init (int V_0, //local Program.S1 V_1) //s1 IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ldloca.s V_1 IL_0012: initobj ""Program.S1"" IL_0018: ldloca.s V_1 IL_001a: ldc.i4.s 42 IL_001c: stfld ""int Program.S1.X"" IL_0021: ldloca.s V_1 IL_0023: ldloca.s V_1 IL_0025: call ""Program.S1 Program.S1.op_Addition(in Program.S1, in Program.S1)"" IL_002a: stloc.1 IL_002b: ldloc.1 IL_002c: ldfld ""int Program.S1.X"" IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: ret }"); } [Fact] public void InParamPassRValue() { var text = @" class Program { public static void Main() { System.Console.WriteLine(M(42)); System.Console.WriteLine(new Program()[5, 6]); System.Console.WriteLine(M(42)); System.Console.WriteLine(M(42)); } static ref readonly int M(in int x) { return ref x; } int this[in int x, in int y] => x + y; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"42 11 42 42"); comp.VerifyIL("Program.Main()", @" { // Code size 72 (0x48) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: newobj ""Program..ctor()"" IL_0015: ldc.i4.5 IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldc.i4.6 IL_001a: stloc.1 IL_001b: ldloca.s V_1 IL_001d: call ""int Program.this[in int, in int].get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ldc.i4.s 42 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: call ""ref readonly int Program.M(in int)"" IL_0031: ldind.i4 IL_0032: call ""void System.Console.WriteLine(int)"" IL_0037: ldc.i4.s 42 IL_0039: stloc.0 IL_003a: ldloca.s V_0 IL_003c: call ""ref readonly int Program.M(in int)"" IL_0041: ldind.i4 IL_0042: call ""void System.Console.WriteLine(int)"" IL_0047: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamPassRoField() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(F)); } static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); comp = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "42", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); comp.VerifyIL("Program.Main()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) IL_0000: ldsfld ""int Program.F"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""ref readonly int Program.M(in int)"" IL_000d: ldind.i4 IL_000e: call ""void System.Console.WriteLine(int)"" IL_0013: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamPassRoField1() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(in F)); } static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); comp = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "42", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); } [Fact] public void InParamPassRoParamReturn() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(F)); } static ref readonly int M(in int x) { return ref M1(x); } static ref readonly int M1(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.M(in int)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref readonly int Program.M1(in int)"" IL_0006: ret }"); } [Fact] public void InParamBase() { var text = @" class Program { public static readonly string S = ""hi""; public string SI; public static void Main() { var p = new P1(S); System.Console.WriteLine(p.SI); System.Console.WriteLine(p.M(42)); } public Program(in string x) { SI = x; } public virtual ref readonly int M(in int x) { return ref x; } } class P1 : Program { public P1(in string x) : base(x){} public override ref readonly int M(in int x) { return ref base.M(x); } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hi 42"); comp.VerifyIL("P1..ctor(in string)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""Program..ctor(in string)"" IL_0007: ret }"); comp.VerifyIL("P1.M(in int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""ref readonly int Program.M(in int)"" IL_0007: ret }"); } [Fact] public void RefReturnParamAccess1() { var text = @" class Program { static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void InParamCannotAssign() { var text = @" class Program { static void M(in int arg1, in (int Alice, int Bob) arg2) { arg1 = 1; arg2.Alice = 2; arg1 ++; arg2.Alice --; arg1 += 1; arg2.Alice -= 2; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 = 1; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(6, 9), // (7,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice = 2; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(7, 9), // (9,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 ++; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(9, 9), // (10,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice --; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(10, 9), // (12,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 += 1; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int"), // (13,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice -= 2; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)")); } [Fact] public void InParamCannotRefReturn() { var text = @" class Program { static ref readonly int M1_baseline(in int arg1, in (int Alice, int Bob) arg2) { // valid return ref arg1; } static ref readonly int M2_baseline(in int arg1, in (int Alice, int Bob) arg2) { // valid return ref arg2.Alice; } static ref int M1(in int arg1, in (int Alice, int Bob) arg2) { return ref arg1; } static ref int M2(in int arg1, in (int Alice, int Bob) arg2) { return ref arg2.Alice; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (18,20): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg1; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(18, 20), // (23,20): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(23, 20) ); } [Fact] public void InParamCannotAssignByref() { var text = @" class Program { static void M(in int arg1, in (int Alice, int Bob) arg2) { ref var y = ref arg1; ref int a = ref arg2.Alice; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,25): error CS8406: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // ref var y = ref arg1; Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "arg1").WithArguments("variable", "in int"), // (7,25): error CS8407: Members of variable 'in (int Alice, int Bob)' cannot be used as a ref or out value because it is a readonly variable // ref int a = ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void InParamCannotTakePtr() { var text = @" class Program { unsafe static void M(in int arg1, in (int Alice, int Bob) arg2) { int* a = & arg1; int* b = & arg2.Alice; fixed(int* c = & arg1) { } fixed(int* d = & arg2.Alice) { } } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* a = & arg1; Diagnostic(ErrorCode.ERR_FixedNeeded, "& arg1").WithLocation(6, 18), // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* b = & arg2.Alice; Diagnostic(ErrorCode.ERR_FixedNeeded, "& arg2.Alice").WithLocation(7, 18) ); } [Fact] public void InParamCannotReturnByOrdinaryRef() { var text = @" class Program { static ref int M(in int arg1, in (int Alice, int Bob) arg2) { bool b = true; if (b) { return ref arg1; } else { return ref arg2.Alice; } } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (10,24): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg1; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(10, 24), // (14,24): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(14, 24) ); } [Fact] public void InParamCanReturnByRefReadonly() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { bool b = true; if (b) { return ref arg1; } else { return ref arg2.Alice; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: brfalse.s IL_0005 IL_0003: ldarg.0 IL_0004: ret IL_0005: ldarg.1 IL_0006: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_000b: ret }"); } [Fact, WorkItem(18357, "https://github.com/dotnet/roslyn/issues/18357")] public void InParamCanReturnByRefReadonlyNested() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { ref readonly int M1(in int arg11, in (int Alice, int Bob) arg21) { bool b = true; if (b) { return ref arg11; } else { return ref arg21.Alice; } } return ref M1(arg1, arg2); } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.<M>g__M1|0_0(in int, in System.ValueTuple<int, int>)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: brfalse.s IL_0005 IL_0003: ldarg.0 IL_0004: ret IL_0005: ldarg.1 IL_0006: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_000b: ret }"); } [Fact, WorkItem(18357, "https://github.com/dotnet/roslyn/issues/18357")] public void InParamCannotReturnByRefNested() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { ref int M1(in int arg11, in (int Alice, int Bob) arg21) { bool b = true; if (b) { return ref arg11; } else { return ref arg21.Alice; } } return ref M1(arg1, arg2); } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (12,28): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg11; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg11").WithArguments("variable", "in int").WithLocation(12, 28), // (16,28): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg21.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg21.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(16, 28) ); } [Fact] public void InParamOptional() { var text = @" class Program { static void Main() { System.Console.WriteLine(M()); } static int M(in int x = 42) => x; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"42"); comp.VerifyIL("Program.Main", @" { // Code size 16 (0x10) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""int Program.M(in int)"" IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ret }"); } [Fact] public void InParamConv() { var text = @" class Program { static void Main() { var arg = 42; System.Console.WriteLine(M(arg)); } static double M(in double x) => x; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"42"); comp.VerifyIL("Program.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init (double V_0) IL_0000: ldc.i4.s 42 IL_0002: conv.r8 IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""double Program.M(in double)"" IL_000b: call ""void System.Console.WriteLine(double)"" IL_0010: ret }"); } [Fact] public void InParamAsyncSpill1() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { M1(1, await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"6"); } [Fact] public void ReadonlyParamAsyncSpillIn() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(in RefReturning(ref local), await GetT(2), 3); } private static ref int RefReturning(ref int arg) { return ref arg; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp.VerifyEmitDiagnostics( // (14,19): error CS8178: 'await' cannot be used in an expression containing a call to 'Program.RefReturning(ref int)' because it returns by reference // M1(in RefReturning(ref local), await GetT(2), 3); Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "RefReturning(ref local)").WithArguments("Program.RefReturning(ref int)").WithLocation(14, 19) ); } [Fact] public void ReadonlyParamAsyncSpillIn2() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(arg3: 3, arg1: RefReturning(ref local), arg2: await GetT(2)); } private static ref int RefReturning(ref int arg) { return ref arg; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var verifier = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "6"); verifier.VerifyIL("Program.<Test>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 180 (0xb4) .maxstack 3 .locals init (int V_0, int V_1, //local int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, int V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldc.i4.1 IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldloca.s V_1 IL_000f: call ""ref int Program.RefReturning(ref int)"" IL_0014: ldind.i4 IL_0015: stfld ""int Program.<Test>d__1.<>7__wrap1"" IL_001a: ldc.i4.2 IL_001b: call ""System.Threading.Tasks.Task<int> Program.GetT<int>(int)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.3 IL_0026: ldloca.s V_3 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Test>d__1.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.3 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_0045: ldloca.s V_3 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Test>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Test>d__1)"" IL_004d: leave.s IL_00b3 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_0055: stloc.3 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Test>d__1.<>1__state"" IL_006b: ldloca.s V_3 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.2 IL_0073: ldarg.0 IL_0074: ldflda ""int Program.<Test>d__1.<>7__wrap1"" IL_0079: ldloca.s V_2 IL_007b: ldc.i4.3 IL_007c: stloc.s V_4 IL_007e: ldloca.s V_4 IL_0080: call ""void Program.M1(in int, in int, in int)"" IL_0085: leave.s IL_00a0 } catch System.Exception { IL_0087: stloc.s V_5 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Program.<Test>d__1.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_0097: ldloc.s V_5 IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009e: leave.s IL_00b3 } IL_00a0: ldarg.0 IL_00a1: ldc.i4.s -2 IL_00a3: stfld ""int Program.<Test>d__1.<>1__state"" IL_00a8: ldarg.0 IL_00a9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b3: ret }"); } [Fact] public void ReadonlyParamAsyncSpillInRoField() { var text = @" using System.Threading.Tasks; class Program { public static readonly int F = 5; static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(in F, await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); MutateReadonlyField(); return val; } private static unsafe void MutateReadonlyField() { fixed(int* ptr = &F) { *ptr = 42; } } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseExe); var result = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @"47"); var expectedIL = @" { // Code size 162 (0xa2) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, int V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__2.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003f IL_000a: ldc.i4.2 IL_000b: call ""System.Threading.Tasks.Task<int> Program.GetT<int>(int)"" IL_0010: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0015: stloc.2 IL_0016: ldloca.s V_2 IL_0018: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001d: brtrue.s IL_005b IL_001f: ldarg.0 IL_0020: ldc.i4.0 IL_0021: dup IL_0022: stloc.0 IL_0023: stfld ""int Program.<Test>d__2.<>1__state"" IL_0028: ldarg.0 IL_0029: ldloc.2 IL_002a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_002f: ldarg.0 IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_0035: ldloca.s V_2 IL_0037: ldarg.0 IL_0038: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Test>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Test>d__2)"" IL_003d: leave.s IL_00a1 IL_003f: ldarg.0 IL_0040: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_0045: stloc.2 IL_0046: ldarg.0 IL_0047: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_004c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0052: ldarg.0 IL_0053: ldc.i4.m1 IL_0054: dup IL_0055: stloc.0 IL_0056: stfld ""int Program.<Test>d__2.<>1__state"" IL_005b: ldloca.s V_2 IL_005d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0062: stloc.1 IL_0063: ldsflda ""int Program.F"" IL_0068: ldloca.s V_1 IL_006a: ldc.i4.3 IL_006b: stloc.3 IL_006c: ldloca.s V_3 IL_006e: call ""void Program.M1(in int, in int, in int)"" IL_0073: leave.s IL_008e } catch System.Exception { IL_0075: stloc.s V_4 IL_0077: ldarg.0 IL_0078: ldc.i4.s -2 IL_007a: stfld ""int Program.<Test>d__2.<>1__state"" IL_007f: ldarg.0 IL_0080: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_0085: ldloc.s V_4 IL_0087: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008c: leave.s IL_00a1 } IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Test>d__2.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a1: ret } "; result.VerifyIL("Program.<Test>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", expectedIL); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); result = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @"47"); result.VerifyIL("Program.<Test>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", expectedIL); } [Fact] public void InParamAsyncSpill2() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { M1(await GetT(1), await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"6"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillMethods() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f M1(GetLocal(ref local).f, 42, GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of calls M1(GetLocal(ref local).f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillMethodsWriteable() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f M1(GetLocalWriteable(ref local).f, 42, GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of calls M1(GetLocalWriteable(ref local).f, await GetT(42), GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); } private static ref S1 GetLocalWriteable(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillStructField() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling M1(local.f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] public void InParamAsyncSpillClassField() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling M1(local.f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public class S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] public void InParamAsyncSpillExtension() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling local.f.M1(await GetT(42), GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); } private static ref S1 GetLocalWriteable(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } static class Ext { public static void M1(in this int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamAsyncSpillReadOnlyStructThis() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f GetLocal(ref local).M1( 42, GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of a call GetLocal(ref local).M1(await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of a call GetLocalWriteable(ref local).M1(await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local = new S1(local.f + 1); return ref local; } private static ref S1 GetLocalWriteable(ref S1 local) { local = new S1(local.f + 1); return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } public readonly struct S1 { public readonly int f; public S1(int val) { this.f = val; } public void M1(in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(this.f); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3 1 42 3 3"); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 2 3 1 42 2 3 1 42 2 3"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamAsyncSpillReadOnlyStructThis_NoValCapture() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static readonly S1 s1 = new S1(1); public static readonly S1 s2 = new S1(2); public static readonly S1 s3 = new S1(3); public static readonly S1 s4 = new S1(4); public static async Task Test() { s1.M1(s2, await GetT(s3), s4); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } public readonly struct S1 { public readonly int f; public S1(int val) { this.f = val; } public void M1(in S1 arg2, in S1 arg3, in S1 arg4) { System.Console.WriteLine(this.f); System.Console.WriteLine(arg2.f); System.Console.WriteLine(arg3.f); System.Console.WriteLine(arg4.f); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 1 2 3 4"); // NOTE: s1, s3 and s4 are all directly loaded via ldsflda and not spilled. v.VerifyIL("Program.<Test>d__5.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 170 (0xaa) .maxstack 4 .locals init (int V_0, S1 V_1, System.Runtime.CompilerServices.TaskAwaiter<S1> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__5.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldsfld ""S1 Program.s3"" IL_000f: call ""System.Threading.Tasks.Task<S1> Program.GetT<S1>(S1)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<S1> System.Threading.Tasks.Task<S1>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<S1>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Test>d__5.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<S1>, Program.<Test>d__5>(ref System.Runtime.CompilerServices.TaskAwaiter<S1>, ref Program.<Test>d__5)"" IL_0041: leave.s IL_00a9 IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<S1>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Test>d__5.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""S1 System.Runtime.CompilerServices.TaskAwaiter<S1>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsflda ""S1 Program.s1"" IL_006c: ldsflda ""S1 Program.s2"" IL_0071: ldloca.s V_1 IL_0073: ldsflda ""S1 Program.s4"" IL_0078: call ""void S1.M1(in S1, in S1, in S1)"" IL_007d: leave.s IL_0096 } catch System.Exception { IL_007f: stloc.3 IL_0080: ldarg.0 IL_0081: ldc.i4.s -2 IL_0083: stfld ""int Program.<Test>d__5.<>1__state"" IL_0088: ldarg.0 IL_0089: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_008e: ldloc.3 IL_008f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0094: leave.s IL_00a9 } IL_0096: ldarg.0 IL_0097: ldc.i4.s -2 IL_0099: stfld ""int Program.<Test>d__5.<>1__state"" IL_009e: ldarg.0 IL_009f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_00a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a9: ret } "); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); v = CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @" 1 2 3 4"); // NOTE: s1, s3 and s4 are all directly loaded via ldsflda and not spilled. v.VerifyIL("Program.<Test>d__5.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 183 (0xb7) .maxstack 4 .locals init (int V_0, S1 V_1, System.Runtime.CompilerServices.TaskAwaiter<S1> V_2, S1 V_3, S1 V_4, S1 V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__5.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldsfld ""S1 Program.s3"" IL_000f: call ""System.Threading.Tasks.Task<S1> Program.GetT<S1>(S1)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<S1> System.Threading.Tasks.Task<S1>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<S1>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Test>d__5.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<S1>, Program.<Test>d__5>(ref System.Runtime.CompilerServices.TaskAwaiter<S1>, ref Program.<Test>d__5)"" IL_0041: leave.s IL_00b6 IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<S1>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Test>d__5.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""S1 System.Runtime.CompilerServices.TaskAwaiter<S1>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsfld ""S1 Program.s1"" IL_006c: stloc.3 IL_006d: ldloca.s V_3 IL_006f: ldsfld ""S1 Program.s2"" IL_0074: stloc.s V_4 IL_0076: ldloca.s V_4 IL_0078: ldloca.s V_1 IL_007a: ldsfld ""S1 Program.s4"" IL_007f: stloc.s V_5 IL_0081: ldloca.s V_5 IL_0083: call ""void S1.M1(in S1, in S1, in S1)"" IL_0088: leave.s IL_00a3 } catch System.Exception { IL_008a: stloc.s V_6 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Program.<Test>d__5.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_009a: ldloc.s V_6 IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a1: leave.s IL_00b6 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Program.<Test>d__5.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_00b1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b6: ret } "); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10834")] public void InParamGenericReadonly() { var text = @" class Program { static void Main(string[] args) { var o = new D(); var s = new S1(); o.M1(s); // should not be mutated. System.Console.WriteLine(s.field); } } abstract class C<U> { public abstract void M1<T>(in T arg) where T : U, I1; } class D: C<S1> { public override void M1<T>(in T arg) { arg.M3(); } } public struct S1: I1 { public int field; public void M3() { field = 42; } } interface I1 { void M3(); } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"0"); comp.VerifyIL("D.M1<T>(in T)", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldobj ""T"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I1.M3()"" IL_0014: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10834")] public void InParamGenericReadonlyROstruct() { var text = @" class Program { static void Main(string[] args) { var o = new D(); var s = new S1(); o.M1(s); } } abstract class C<U> { public abstract void M1<T>(in T arg) where T : U, I1; } class D: C<S1> { public override void M1<T>(in T arg) { arg.M3(); } } public readonly struct S1: I1 { public void M3() { } } interface I1 { void M3(); } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @""); comp.VerifyIL("D.M1<T>(in T)", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldobj ""T"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I1.M3()"" IL_0014: ret }"); } [Fact] public void RefReadOnlyOptionalParameters() { CompileAndVerify(@" using System; class Program { static void Print(in int p = 5) { Console.Write(p); } static void Main() { Print(); Console.Write(""-""); Print(9); } }", expectedOutput: "5-9"); } [WorkItem(23338, "https://github.com/dotnet/roslyn/issues/23338")] [Fact] public void InParamsNullable() { var text = @" class Program { static void Main(string[] args) { S1 s = new S1(); s.val = 42; S1? ns = s; Test1(in ns); Test2(ref ns); } static void Test1(in S1? arg) { // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); // should not mutate arg.ToString(); // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); } static void Test2(ref S1? arg) { // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); // can mutate arg.ToString(); // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); } } struct S1 { public int val; public override string ToString() { var result = val.ToString(); val = 0; return result; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242420"); comp.VerifyIL("Program.Test1(in S1?)", @" { // Code size 54 (0x36) .maxstack 1 .locals init (S1? V_0) IL_0000: ldarg.0 IL_0001: call ""S1 S1?.GetValueOrDefault()"" IL_0006: box ""S1"" IL_000b: call ""void System.Console.Write(object)"" IL_0010: ldarg.0 IL_0011: ldobj ""S1?"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: constrained. ""S1?"" IL_001f: callvirt ""string object.ToString()"" IL_0024: pop IL_0025: ldarg.0 IL_0026: call ""S1 S1?.GetValueOrDefault()"" IL_002b: box ""S1"" IL_0030: call ""void System.Console.Write(object)"" IL_0035: ret }"); comp.VerifyIL("Program.Test2(ref S1?)", @" { // Code size 46 (0x2e) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""S1 S1?.GetValueOrDefault()"" IL_0006: box ""S1"" IL_000b: call ""void System.Console.Write(object)"" IL_0010: ldarg.0 IL_0011: constrained. ""S1?"" IL_0017: callvirt ""string object.ToString()"" IL_001c: pop IL_001d: ldarg.0 IL_001e: call ""S1 S1?.GetValueOrDefault()"" IL_0023: box ""S1"" IL_0028: call ""void System.Console.Write(object)"" IL_002d: ret }"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(in Test a, in Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary_Right() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(Test a, in Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary_Left() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(in Test a, Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Unary() { var reference = CreateCompilation(@" public class Test { public bool Value { get; set; } public static bool operator !(in Test a) { return !a.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = true }; System.Console.WriteLine(!a); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "False"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "False"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Conversion() { var reference = CreateCompilation(@" public class Test { public bool Value { get; set; } public static explicit operator int(in Test a) { return a.Value ? 3 : 5; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = true }; System.Console.WriteLine((int)a); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "3"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "3"); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_NoArgs() { var code = @" class Program { static void Test(in int value = 5) { System.Console.WriteLine(value); } static void Main(string[] args) { /*<bind>*/Test()/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "5").VerifyIL("Program.Main", @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""void Program.Test(in int)"" IL_0009: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test()') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_OneArg() { var code = @" class Program { static void Test(in int value = 5) { System.Console.WriteLine(value); } static void Main(string[] args) { /*<bind>*/Test(10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "10").VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""void Program.Test(in int)"" IL_000a: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(10)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_NoArgs() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test()/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(1, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: value1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'Test()') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test()') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_OneArg() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(2)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(2, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(2)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test(2)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test(2)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_TwoArgs() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(3, 10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(3, 10)").VerifyIL("Program.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 10 IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void Program.Test(in int, in int)"" IL_000e: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(3, 10)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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: value2) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Required_Optional_OneArg() { var code = @" class Program { static void Test(in int value1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(1)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(1, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test(in System.Int32 value1, [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test(1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test(1)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Required_Optional_TwoArgs() { var code = @" class Program { static void Test(in int value1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(2, 10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(2, 10)").VerifyIL("Program.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 10 IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void Program.Test(in int, in int)"" IL_000e: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test(in System.Int32 value1, [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(2, 10)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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: value2) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Optional_Optional_OneArg() { var code = @" class Program { public int this[in int p1 = 1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[3]/*<bind>*/ += 10; } }"; CompileAndVerify(code, expectedOutput: @" get p1=3 p2=2 set p1=3 p2=2 to 10 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.3 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.3 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.2 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 10 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[[in System.Int32 p1 = 1], [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[3]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'obj[3]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'obj[3]') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Optional_Optional_TwoArgs() { var code = @" class Program { public int this[in int p1 = 1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[4, 5]/*<bind>*/ += 11; } }"; CompileAndVerify(code, expectedOutput: @" get p1=4 p2=5 set p1=4 p2=5 to 11 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.4 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.5 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.4 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.5 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 11 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[[in System.Int32 p1 = 1], [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[4, 5]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '4') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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: p2) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Required_Optional_OneArg() { var code = @" class Program { public int this[in int p1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[3]/*<bind>*/ += 10; } }"; CompileAndVerify(code, expectedOutput: @" get p1=3 p2=2 set p1=3 p2=2 to 10 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.3 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.3 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.2 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 10 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[in System.Int32 p1, [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[3]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'obj[3]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'obj[3]') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Required_Optional_TwoArgs() { var code = @" class Program { public int this[in int p1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[4, 5]/*<bind>*/ += 11; } }"; CompileAndVerify(code, expectedOutput: @" get p1=4 p2=5 set p1=4 p2=5 to 11 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.4 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.5 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.4 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.5 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 11 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[in System.Int32 p1, [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[4, 5]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '4') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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: p2) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void Issue23691_PassingInOptionalArgumentsByRef_OneArg() { var code = @" class Program { static void Main() { /*<bind>*/A(1)/*<bind>*/; } static void A(in double x = 1, in string y = ""test"") => System.Console.WriteLine(y); static void B(in float x, in float y, in float z = 3.0f) => System.Console.WriteLine(x * y * z); }"; CompileAndVerify(code, expectedOutput: "test").VerifyIL("Program.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (double V_0, string V_1) IL_0000: ldc.r8 1 IL_0009: stloc.0 IL_000a: ldloca.s V_0 IL_000c: ldstr ""test"" IL_0011: stloc.1 IL_0012: ldloca.s V_1 IL_0014: call ""void Program.A(in double, in string)"" IL_0019: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.A([in System.Double x = 1], [in System.String y = ""test""])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'A(1)') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"", IsImplicit) (Syntax: 'A(1)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void Issue23691_PassingInOptionalArgumentsByRef_TwoArgs() { var code = @" class Program { static void Main() { /*<bind>*/B(1, 2)/*<bind>*/; } static void A(in double x = 1, in string y = ""test"") => System.Console.WriteLine(y); static void B(in float x, in float y, in float z = 3.0f) => System.Console.WriteLine(x * y * z); }"; CompileAndVerify(code, expectedOutput: "6").VerifyIL("Program.Main", @" { // Code size 30 (0x1e) .maxstack 3 .locals init (float V_0, float V_1, float V_2) IL_0000: ldc.r4 1 IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: ldc.r4 2 IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldc.r4 3 IL_0015: stloc.2 IL_0016: ldloca.s V_2 IL_0018: call ""void Program.B(in float, in float, in float)"" IL_001d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.B(in System.Single x, in System.Single y, [in System.Single z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'B(1, 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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.DefaultValue, Matching Parameter: z) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'B(1, 2)') ILiteralOperation (OperationKind.Literal, Type: System.Single, Constant: 3, IsImplicit) (Syntax: 'B(1, 2)') 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)", DiagnosticDescription.None); } [WorkItem(23692, "https://github.com/dotnet/roslyn/issues/23692")] [Fact] public void ThisToInParam() { var code = @" using System; static class Ex { public static void InMethod(in X arg) => Console.Write(arg); } class X { public void M() { // pass `this` by in-parameter. Ex.InMethod(this); } } class Program { static void Main() { var x = new X(); // baseline Ex.InMethod(x); x.M(); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "XX"); verifier.VerifyIL("X.M()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""void Ex.InMethod(in X)"" IL_0007: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_Local() { var code = @" using System; public class Test { static void Main(string[] args) { int x = 50; Moo(x + 0, () => x = 60); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 41 (0x29) .maxstack 3 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.s 50 IL_0009: stfld ""int Test.<>c__DisplayClass0_0.x"" IL_000e: ldloc.0 IL_000f: ldfld ""int Test.<>c__DisplayClass0_0.x"" IL_0014: stloc.1 IL_0015: ldloca.s V_1 IL_0017: ldloc.0 IL_0018: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_001e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0023: call ""void Test.Moo(in int, System.Action)"" IL_0028: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ArrayAccess() { var code = @" using System; public class Test { static void Main(string[] args) { int[] x = new int[] { 50 }; Moo(x[0] + 0, () => x[0] = 60); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 52 (0x34) .maxstack 5 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 50 IL_0011: stelem.i4 IL_0012: stfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_0017: ldloc.0 IL_0018: ldfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_001d: ldc.i4.0 IL_001e: ldelem.i4 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: call ""void Test.Moo(in int, System.Action)"" IL_0033: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ArrayAccessReordered() { var code = @" using System; public class Test { static void Main(string[] args) { int[] x = new int[] { 50 }; Moo(change: () => x[0] = 60, y: x[0] + 0); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 52 (0x34) .maxstack 5 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 50 IL_0011: stelem.i4 IL_0012: stfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_0017: ldloc.0 IL_0018: ldfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_001d: ldc.i4.0 IL_001e: ldelem.i4 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: call ""void Test.Moo(in int, System.Action)"" IL_0033: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_FieldAcces() { var code = @" using System; public class Test { struct S1 { public int x; } static S1 s = new S1 { x = 555 }; static void Main(string[] args) { Moo(s.x + 0); } static void Moo(in int y) { Console.Write(y); s.x = 123; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "555555"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int V_0) IL_0000: ldsflda ""Test.S1 Test.s"" IL_0005: ldfld ""int Test.S1.x"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: call ""void Test.Moo(in int)"" IL_0012: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_RoFieldAcces() { var code = @" using System; public class Test { struct S1 { public int x; } readonly S1 s; static void Main(string[] args) { var x = new Test(); } public Test() { Test1(s.x + 0, ref s.x); } private void Test1(in int y, ref int f) { Console.Write(y); f = 1; Console.Write(y); Test2(s.x + 0, ref f); } private void Test2(in int y, ref int f) { Console.Write(y); f = 2; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "0011", verify: Verification.Fails); verifier.VerifyIL("Test..ctor()", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: ldflda ""Test.S1 Test.s"" IL_000d: ldfld ""int Test.S1.x"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: ldarg.0 IL_0016: ldflda ""Test.S1 Test.s"" IL_001b: ldflda ""int Test.S1.x"" IL_0020: call ""void Test.Test1(in int, ref int)"" IL_0025: ret } "); verifier.VerifyIL("Test.Test1(in int, ref int)", @" { // Code size 39 (0x27) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldind.i4 IL_0002: call ""void System.Console.Write(int)"" IL_0007: ldarg.2 IL_0008: ldc.i4.1 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldind.i4 IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldarg.0 IL_0013: ldflda ""Test.S1 Test.s"" IL_0018: ldfld ""int Test.S1.x"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: ldarg.2 IL_0021: call ""void Test.Test2(in int, ref int)"" IL_0026: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ThisAcces() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } public Test() { Test3(null ?? this); } private void Test3(in Test y) { } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: ""); verifier.VerifyIL("Test..ctor()", @" { // Code size 17 (0x11) .maxstack 2 .locals init (Test V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: stloc.0 IL_0009: ldloca.s V_0 IL_000b: call ""void Test.Test3(in Test)"" IL_0010: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_RefMethod() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } private string s = ""hi""; private ref string M1() { return ref s; } public Test() { Test3(null ?? M1()); } private void Test3(in string y) { Console.Write(y); s = ""bye""; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "hihi"); verifier.VerifyIL("Test..ctor()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: ldstr ""hi"" IL_0006: stfld ""string Test.s"" IL_000b: ldarg.0 IL_000c: call ""object..ctor()"" IL_0011: ldarg.0 IL_0012: ldarg.0 IL_0013: call ""ref string Test.M1()"" IL_0018: ldind.ref IL_0019: stloc.0 IL_001a: ldloca.s V_0 IL_001c: call ""void Test.Test3(in string)"" IL_0021: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperator() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } private static string s = ""hi""; public Test() { var dummy = (null ?? s) + this; } public static string operator +(in string y, in Test t) { Console.Write(y); s = ""bye""; Console.Write(y); return y; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "hihi"); verifier.VerifyIL("Test..ctor()", @" { // Code size 23 (0x17) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldsfld ""string Test.s"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldarga.s V_0 IL_0010: call ""string Test.op_Addition(in string, in Test)"" IL_0015: pop IL_0016: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperatorLifted() { var code = @" using System; public struct Test { static void Main(string[] args) { var x = new Test(); x.Test1(); } private Action change; public Test(Action change) { this.change = change; } public void Test1() { int s = 1; Test? t = new Test(() => s = 42); var dummy = s + t; } public static int operator +(in int y, in Test t) { Console.Write(y); t.change(); Console.Write(y); return 88; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "11"); verifier.VerifyIL("Test.Test1()", @" { // Code size 71 (0x47) .maxstack 2 .locals init (Test.<>c__DisplayClass3_0 V_0, //CS$<>8__locals0 int V_1, Test? V_2, Test V_3) IL_0000: newobj ""Test.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld ""int Test.<>c__DisplayClass3_0.s"" IL_000d: ldloc.0 IL_000e: ldftn ""void Test.<>c__DisplayClass3_0.<Test1>b__0()"" IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0019: newobj ""Test..ctor(System.Action)"" IL_001e: newobj ""Test?..ctor(Test)"" IL_0023: ldloc.0 IL_0024: ldfld ""int Test.<>c__DisplayClass3_0.s"" IL_0029: stloc.1 IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool Test?.HasValue.get"" IL_0032: brfalse.s IL_0046 IL_0034: ldloca.s V_1 IL_0036: ldloca.s V_2 IL_0038: call ""Test Test?.GetValueOrDefault()"" IL_003d: stloc.3 IL_003e: ldloca.s V_3 IL_0040: call ""int Test.op_Addition(in int, in Test)"" IL_0045: pop IL_0046: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperatorUnary() { var code = @" using System; public class Test { static void Main(string[] args) { Test1(); } private static Test s = new Test(); public static void Test1() { var dummy = +(null ?? s); } public static Test operator +(in Test y) { Console.Write(y); s = default; Console.Write(y); return y; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "TestTest"); verifier.VerifyIL("Test.Test1()", @" { // Code size 15 (0xf) .maxstack 1 .locals init (Test V_0) IL_0000: ldsfld ""Test Test.s"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""Test Test.op_UnaryPlus(in Test)"" IL_000d: pop IL_000e: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InConversion() { var code = @" using System; public class Test { static void Main(string[] args) { Test1(); } private static Test s = new Test(); public static void Test1() { int dummyI = (null ?? s); s = new Derived(); long dummyL = (null ?? s); } public static implicit operator int(in Test y) { Console.Write(y.ToString()); s = default; Console.Write(y.ToString()); return 1; } } class Derived : Test { } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "TestTestDerivedDerived"); verifier.VerifyIL("Test.Test1()", @" { // Code size 39 (0x27) .maxstack 1 .locals init (Test V_0) IL_0000: ldsfld ""Test Test.s"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""int Test.op_Implicit(in Test)"" IL_000d: pop IL_000e: newobj ""Derived..ctor()"" IL_0013: stsfld ""Test Test.s"" IL_0018: ldsfld ""Test Test.s"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: call ""int Test.op_Implicit(in Test)"" IL_0025: pop IL_0026: ret } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenInParametersTests : CompilingTestBase { [Fact] public void ThreeParamReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { M(y: in GetField(0).X, z: GetField(1).X, x: GetField(2).X); } static void M(in int x, in int y, in int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }", expectedOutput: @"GetField 0 0 GetField 1 1 GetField 2 2 3 3 3"); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: stloc.1 IL_0018: ldc.i4.2 IL_0019: call ""ref C.S C.GetField(int)"" IL_001e: ldflda ""int C.S.X"" IL_0023: ldloc.0 IL_0024: ldloc.1 IL_0025: call ""void C.M(in int, in int, in int)"" IL_002a: ret }"); } [Fact] public void InParamReadonlyFieldReorder() { var comp = CompileAndVerify(@" using System; class C { private static readonly int _f = 0; public C() { M(y: _f, x: _f + 1); M(y: in _f, x: _f + 1); } public static void Main() { M(y: _f, x: _f + 1); M(y: in _f, x: _f + 1); _ = new C(); } static void M(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0 1 0 1 0 1 0", verify: Verification.Fails); comp.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 2 .locals init (int& V_0, int V_1) IL_0000: ldsflda ""int C._f"" IL_0005: stloc.0 IL_0006: ldsfld ""int C._f"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldloc.0 IL_0011: call ""void C.M(in int, in int)"" IL_0016: ldsflda ""int C._f"" IL_001b: stloc.0 IL_001c: ldsfld ""int C._f"" IL_0021: ldc.i4.1 IL_0022: add IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void C.M(in int, in int)"" IL_002c: newobj ""C..ctor()"" IL_0031: pop IL_0032: ret }"); } [Fact] public void InParamCallOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; M(in x); } static void M(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.0 IL_0005: call ""void C.M(in int, int)"" IL_000a: ret }"); } [Fact] public void InParamCtorOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; new C(in x); } public C(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 12 (0xc) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.0 IL_0005: newobj ""C..ctor(in int, int)"" IL_000a: pop IL_000b: ret }"); } [Fact] public void InParamInitializerOptionalArg() { var comp = CompileAndVerify(@" using System; class C { public static int _x = 1; public int _f = M(in _x); public static void Main() { new C(); } public static int M(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); return x; } }", expectedOutput: @"1 0"); comp.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldsflda ""int C._x"" IL_0006: ldc.i4.0 IL_0007: call ""int C.M(in int, int)"" IL_000c: stfld ""int C._f"" IL_0011: ldarg.0 IL_0012: call ""object..ctor()"" IL_0017: ret }"); } [Fact] public void InParamCollectionInitializerOptionalArg() { var comp = CompileAndVerify(@" using System; using System.Collections; class C : IEnumerable { public static void Main() { int x = 1; new C() { x }; } public IEnumerator GetEnumerator() => null; public void Add(in int x, int y = 0) { Console.WriteLine(x); Console.WriteLine(y); } }"); comp.VerifyIL("C.Main", @" { // Code size 16 (0x10) .maxstack 3 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.0 IL_000a: callvirt ""void C.Add(in int, int)"" IL_000f: ret }"); } [Fact] public void InParamSetter() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C()[in _f] = 0; } public IEnumerator GetEnumerator() => null; public int this[in int x, int y = 0] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); } } }", expectedOutput: @"1 0 2"); comp.VerifyIL("C.Main", @" { // Code size 18 (0x12) .maxstack 4 IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: call ""void C.this[in int, int].set"" IL_0011: ret }"); } [Fact] public void InParamParamsArg() { var comp = CompileAndVerify(@" using System; class C { public static void Main() { int x = 1; M(in x); } public static void M(in int x, params int[] p) { Console.WriteLine(x); Console.WriteLine(p.Length); } }", expectedOutput: @"1 0"); comp.VerifyIL("C.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""int[] System.Array.Empty<int>()"" IL_0009: call ""void C.M(in int, params int[])"" IL_000e: ret }"); } [Fact] public void InParamReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { M(y: in GetField(0).X, x: GetField(1).X); } static void M(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 30 (0x1e) .maxstack 2 .locals init (int& V_0) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: ldloc.0 IL_0018: call ""void C.M(in int, in int)"" IL_001d: ret }"); } [Fact] public void InParamCtorReorder() { var comp = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { new C(y: in GetField(0).X, x: GetField(1).X); } public C(in int x, in int y) { Console.WriteLine(x); Console.WriteLine(y); } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (int& V_0) IL_0000: ldc.i4.0 IL_0001: call ""ref C.S C.GetField(int)"" IL_0006: ldflda ""int C.S.X"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: call ""ref C.S C.GetField(int)"" IL_0012: ldflda ""int C.S.X"" IL_0017: ldloc.0 IL_0018: newobj ""C..ctor(in int, in int)"" IL_001d: pop IL_001e: ret }"); } [Fact] public void InIndexerReorder() { var verifier = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { var c = new C(); _ = c[y: in GetField(0).X, x: in GetField(1).X]; } int this[in int x, in int y] { get { Console.WriteLine(x); Console.WriteLine(y); return x; } } }", expectedOutput: @"GetField 0 0 GetField 1 1 2 2"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (int& V_0) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref C.S C.GetField(int)"" IL_000b: ldflda ""int C.S.X"" IL_0010: stloc.0 IL_0011: ldc.i4.1 IL_0012: call ""ref C.S C.GetField(int)"" IL_0017: ldflda ""int C.S.X"" IL_001c: ldloc.0 IL_001d: callvirt ""int C.this[in int, in int].get"" IL_0022: pop IL_0023: ret }"); } [Fact] public void InIndexerReorderWithCopy() { var verifier = CompileAndVerify(@" using System; class C { public struct S { public int X; } private static S _field; public static ref S GetField(int order) { Console.WriteLine(""GetField "" + _field.X++ + "" "" + order); return ref _field; } public static void Main() { var c = new C(); _ = c[y: GetField(0).X, x: GetField(1).X + 1]; _ = c[y: GetField(0).X + 2, x: GetField(1).X]; } int this[in int x, in int y] { get { Console.WriteLine(x); Console.WriteLine(y); return x; } } }", expectedOutput: @"GetField 0 0 GetField 1 1 3 2 GetField 2 0 GetField 3 1 4 5"); verifier.VerifyIL("C.Main", @" { // Code size 75 (0x4b) .maxstack 4 .locals init (int& V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: call ""ref C.S C.GetField(int)"" IL_000c: ldflda ""int C.S.X"" IL_0011: stloc.0 IL_0012: ldc.i4.1 IL_0013: call ""ref C.S C.GetField(int)"" IL_0018: ldfld ""int C.S.X"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: callvirt ""int C.this[in int, in int].get"" IL_0028: pop IL_0029: ldc.i4.0 IL_002a: call ""ref C.S C.GetField(int)"" IL_002f: ldfld ""int C.S.X"" IL_0034: ldc.i4.2 IL_0035: add IL_0036: stloc.1 IL_0037: ldc.i4.1 IL_0038: call ""ref C.S C.GetField(int)"" IL_003d: ldflda ""int C.S.X"" IL_0042: ldloca.s V_1 IL_0044: callvirt ""int C.this[in int, in int].get"" IL_0049: pop IL_004a: ret }"); } [Fact] public void InParamSetterReorder() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C()[y: in _f, x: _f] = 0; } public IEnumerator GetEnumerator() => null; public int this[in int x, in int y] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); Console.WriteLine(y); } } }", expectedOutput: @"1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 24 (0x18) .maxstack 4 .locals init (int& V_0) IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: stloc.0 IL_000b: ldsflda ""int C._f"" IL_0010: ldloc.0 IL_0011: ldc.i4.0 IL_0012: call ""void C.this[in int, in int].set"" IL_0017: ret }"); } [Fact] public void InParamMemberInitializerReorder() { var comp = CompileAndVerify(@" using System; using System.Collections; class C { static int _f = 1; public static void Main() { new C() { [y: in _f, x: _f] = 0 }; } public IEnumerator GetEnumerator() => null; public int this[in int x, in int y] { get => x; set { Console.WriteLine(x); Console.WriteLine(y); _f++; Console.WriteLine(x); Console.WriteLine(y); } } }", expectedOutput: @"1 1 2 2"); comp.VerifyIL("C.Main", @" { // Code size 26 (0x1a) .maxstack 4 .locals init (int& V_0, int& V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldsflda ""int C._f"" IL_000a: stloc.0 IL_000b: ldsflda ""int C._f"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: callvirt ""void C.this[in int, in int].set"" IL_0019: ret }"); } [Fact] public void RefReturnParamAccess() { var text = @" class Program { static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void InParamPassLValue() { var text = @" struct Program { public static void Main() { var local = 42; System.Console.WriteLine(M(local)); S1 s1 = default(S1); s1.X = 42; s1 += s1; System.Console.WriteLine(s1.X); } static ref readonly int M(in int x) { return ref x; } struct S1 { public int X; public static S1 operator +(in S1 x, in S1 y) { return new S1(){X = x.X + y.X}; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"42 84"); comp.VerifyIL("Program.Main()", @" { // Code size 55 (0x37) .maxstack 2 .locals init (int V_0, //local Program.S1 V_1) //s1 IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ldloca.s V_1 IL_0012: initobj ""Program.S1"" IL_0018: ldloca.s V_1 IL_001a: ldc.i4.s 42 IL_001c: stfld ""int Program.S1.X"" IL_0021: ldloca.s V_1 IL_0023: ldloca.s V_1 IL_0025: call ""Program.S1 Program.S1.op_Addition(in Program.S1, in Program.S1)"" IL_002a: stloc.1 IL_002b: ldloc.1 IL_002c: ldfld ""int Program.S1.X"" IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: ret }"); } [Fact] public void InParamPassRValue() { var text = @" class Program { public static void Main() { System.Console.WriteLine(M(42)); System.Console.WriteLine(new Program()[5, 6]); System.Console.WriteLine(M(42)); System.Console.WriteLine(M(42)); } static ref readonly int M(in int x) { return ref x; } int this[in int x, in int y] => x + y; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"42 11 42 42"); comp.VerifyIL("Program.Main()", @" { // Code size 72 (0x48) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: newobj ""Program..ctor()"" IL_0015: ldc.i4.5 IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldc.i4.6 IL_001a: stloc.1 IL_001b: ldloca.s V_1 IL_001d: call ""int Program.this[in int, in int].get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ldc.i4.s 42 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: call ""ref readonly int Program.M(in int)"" IL_0031: ldind.i4 IL_0032: call ""void System.Console.WriteLine(int)"" IL_0037: ldc.i4.s 42 IL_0039: stloc.0 IL_003a: ldloca.s V_0 IL_003c: call ""ref readonly int Program.M(in int)"" IL_0041: ldind.i4 IL_0042: call ""void System.Console.WriteLine(int)"" IL_0047: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamPassRoField() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(F)); } static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); comp = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "42", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); comp.VerifyIL("Program.Main()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) IL_0000: ldsfld ""int Program.F"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""ref readonly int Program.M(in int)"" IL_000d: ldind.i4 IL_000e: call ""void System.Console.WriteLine(int)"" IL_0013: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamPassRoField1() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(in F)); } static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); comp = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "42", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); comp.VerifyIL("Program.Main()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldsflda ""int Program.F"" IL_0005: call ""ref readonly int Program.M(in int)"" IL_000a: ldind.i4 IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret }"); } [Fact] public void InParamPassRoParamReturn() { var text = @" class Program { public static readonly int F = 42; public static void Main() { System.Console.WriteLine(M(F)); } static ref readonly int M(in int x) { return ref M1(x); } static ref readonly int M1(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: "42"); comp.VerifyIL("Program.M(in int)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref readonly int Program.M1(in int)"" IL_0006: ret }"); } [Fact] public void InParamBase() { var text = @" class Program { public static readonly string S = ""hi""; public string SI; public static void Main() { var p = new P1(S); System.Console.WriteLine(p.SI); System.Console.WriteLine(p.M(42)); } public Program(in string x) { SI = x; } public virtual ref readonly int M(in int x) { return ref x; } } class P1 : Program { public P1(in string x) : base(x){} public override ref readonly int M(in int x) { return ref base.M(x); } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hi 42"); comp.VerifyIL("P1..ctor(in string)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""Program..ctor(in string)"" IL_0007: ret }"); comp.VerifyIL("P1.M(in int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""ref readonly int Program.M(in int)"" IL_0007: ret }"); } [Fact] public void RefReturnParamAccess1() { var text = @" class Program { static ref readonly int M(in int x) { return ref x; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M(in int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void InParamCannotAssign() { var text = @" class Program { static void M(in int arg1, in (int Alice, int Bob) arg2) { arg1 = 1; arg2.Alice = 2; arg1 ++; arg2.Alice --; arg1 += 1; arg2.Alice -= 2; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 = 1; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(6, 9), // (7,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice = 2; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(7, 9), // (9,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 ++; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(9, 9), // (10,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice --; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(10, 9), // (12,9): error CS8408: Cannot assign to variable 'in int' because it is a readonly variable // arg1 += 1; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "arg1").WithArguments("variable", "in int"), // (13,9): error CS8409: Cannot assign to a member of variable 'in (int Alice, int Bob)' because it is a readonly variable // arg2.Alice -= 2; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)")); } [Fact] public void InParamCannotRefReturn() { var text = @" class Program { static ref readonly int M1_baseline(in int arg1, in (int Alice, int Bob) arg2) { // valid return ref arg1; } static ref readonly int M2_baseline(in int arg1, in (int Alice, int Bob) arg2) { // valid return ref arg2.Alice; } static ref int M1(in int arg1, in (int Alice, int Bob) arg2) { return ref arg1; } static ref int M2(in int arg1, in (int Alice, int Bob) arg2) { return ref arg2.Alice; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (18,20): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg1; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(18, 20), // (23,20): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(23, 20) ); } [Fact] public void InParamCannotAssignByref() { var text = @" class Program { static void M(in int arg1, in (int Alice, int Bob) arg2) { ref var y = ref arg1; ref int a = ref arg2.Alice; } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,25): error CS8406: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // ref var y = ref arg1; Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "arg1").WithArguments("variable", "in int"), // (7,25): error CS8407: Members of variable 'in (int Alice, int Bob)' cannot be used as a ref or out value because it is a readonly variable // ref int a = ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void InParamCannotTakePtr() { var text = @" class Program { unsafe static void M(in int arg1, in (int Alice, int Bob) arg2) { int* a = & arg1; int* b = & arg2.Alice; fixed(int* c = & arg1) { } fixed(int* d = & arg2.Alice) { } } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* a = & arg1; Diagnostic(ErrorCode.ERR_FixedNeeded, "& arg1").WithLocation(6, 18), // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* b = & arg2.Alice; Diagnostic(ErrorCode.ERR_FixedNeeded, "& arg2.Alice").WithLocation(7, 18) ); } [Fact] public void InParamCannotReturnByOrdinaryRef() { var text = @" class Program { static ref int M(in int arg1, in (int Alice, int Bob) arg2) { bool b = true; if (b) { return ref arg1; } else { return ref arg2.Alice; } } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (10,24): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg1; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg1").WithArguments("variable", "in int").WithLocation(10, 24), // (14,24): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg2.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg2.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(14, 24) ); } [Fact] public void InParamCanReturnByRefReadonly() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { bool b = true; if (b) { return ref arg1; } else { return ref arg2.Alice; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.M", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: brfalse.s IL_0005 IL_0003: ldarg.0 IL_0004: ret IL_0005: ldarg.1 IL_0006: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_000b: ret }"); } [Fact, WorkItem(18357, "https://github.com/dotnet/roslyn/issues/18357")] public void InParamCanReturnByRefReadonlyNested() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { ref readonly int M1(in int arg11, in (int Alice, int Bob) arg21) { bool b = true; if (b) { return ref arg11; } else { return ref arg21.Alice; } } return ref M1(arg1, arg2); } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails); comp.VerifyIL("Program.<M>g__M1|0_0(in int, in System.ValueTuple<int, int>)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: brfalse.s IL_0005 IL_0003: ldarg.0 IL_0004: ret IL_0005: ldarg.1 IL_0006: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_000b: ret }"); } [Fact, WorkItem(18357, "https://github.com/dotnet/roslyn/issues/18357")] public void InParamCannotReturnByRefNested() { var text = @" class Program { static ref readonly int M(in int arg1, in (int Alice, int Bob) arg2) { ref int M1(in int arg11, in (int Alice, int Bob) arg21) { bool b = true; if (b) { return ref arg11; } else { return ref arg21.Alice; } } return ref M1(arg1, arg2); } } "; var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (12,28): error CS8333: Cannot return variable 'in int' by writable reference because it is a readonly variable // return ref arg11; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "arg11").WithArguments("variable", "in int").WithLocation(12, 28), // (16,28): error CS8334: Members of variable 'in (int Alice, int Bob)' cannot be returned by writable reference because it is a readonly variable // return ref arg21.Alice; Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField2, "arg21.Alice").WithArguments("variable", "in (int Alice, int Bob)").WithLocation(16, 28) ); } [Fact] public void InParamOptional() { var text = @" class Program { static void Main() { System.Console.WriteLine(M()); } static int M(in int x = 42) => x; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"42"); comp.VerifyIL("Program.Main", @" { // Code size 16 (0x10) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""int Program.M(in int)"" IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ret }"); } [Fact] public void InParamConv() { var text = @" class Program { static void Main() { var arg = 42; System.Console.WriteLine(M(arg)); } static double M(in double x) => x; } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"42"); comp.VerifyIL("Program.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init (double V_0) IL_0000: ldc.i4.s 42 IL_0002: conv.r8 IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""double Program.M(in double)"" IL_000b: call ""void System.Console.WriteLine(double)"" IL_0010: ret }"); } [Fact] public void InParamAsyncSpill1() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { M1(1, await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"6"); } [Fact] public void ReadonlyParamAsyncSpillIn() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(in RefReturning(ref local), await GetT(2), 3); } private static ref int RefReturning(ref int arg) { return ref arg; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp.VerifyEmitDiagnostics( // (14,19): error CS8178: 'await' cannot be used in an expression containing a call to 'Program.RefReturning(ref int)' because it returns by reference // M1(in RefReturning(ref local), await GetT(2), 3); Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "RefReturning(ref local)").WithArguments("Program.RefReturning(ref int)").WithLocation(14, 19) ); } [Fact] public void ReadonlyParamAsyncSpillIn2() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(arg3: 3, arg1: RefReturning(ref local), arg2: await GetT(2)); } private static ref int RefReturning(ref int arg) { return ref arg; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var verifier = CompileAndVerify(text, verify: Verification.Fails, expectedOutput: "6"); verifier.VerifyIL("Program.<Test>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 180 (0xb4) .maxstack 3 .locals init (int V_0, int V_1, //local int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, int V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldc.i4.1 IL_000b: stloc.1 IL_000c: ldarg.0 IL_000d: ldloca.s V_1 IL_000f: call ""ref int Program.RefReturning(ref int)"" IL_0014: ldind.i4 IL_0015: stfld ""int Program.<Test>d__1.<>7__wrap1"" IL_001a: ldc.i4.2 IL_001b: call ""System.Threading.Tasks.Task<int> Program.GetT<int>(int)"" IL_0020: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0025: stloc.3 IL_0026: ldloca.s V_3 IL_0028: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002d: brtrue.s IL_006b IL_002f: ldarg.0 IL_0030: ldc.i4.0 IL_0031: dup IL_0032: stloc.0 IL_0033: stfld ""int Program.<Test>d__1.<>1__state"" IL_0038: ldarg.0 IL_0039: ldloc.3 IL_003a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_0045: ldloca.s V_3 IL_0047: ldarg.0 IL_0048: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Test>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Test>d__1)"" IL_004d: leave.s IL_00b3 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_0055: stloc.3 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__1.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<Test>d__1.<>1__state"" IL_006b: ldloca.s V_3 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.2 IL_0073: ldarg.0 IL_0074: ldflda ""int Program.<Test>d__1.<>7__wrap1"" IL_0079: ldloca.s V_2 IL_007b: ldc.i4.3 IL_007c: stloc.s V_4 IL_007e: ldloca.s V_4 IL_0080: call ""void Program.M1(in int, in int, in int)"" IL_0085: leave.s IL_00a0 } catch System.Exception { IL_0087: stloc.s V_5 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Program.<Test>d__1.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_0097: ldloc.s V_5 IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_009e: leave.s IL_00b3 } IL_00a0: ldarg.0 IL_00a1: ldc.i4.s -2 IL_00a3: stfld ""int Program.<Test>d__1.<>1__state"" IL_00a8: ldarg.0 IL_00a9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__1.<>t__builder"" IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b3: ret }"); } [Fact] public void ReadonlyParamAsyncSpillInRoField() { var text = @" using System.Threading.Tasks; class Program { public static readonly int F = 5; static void Main(string[] args) { Test().Wait(); } public static async Task Test() { int local = 1; M1(in F, await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); MutateReadonlyField(); return val; } private static unsafe void MutateReadonlyField() { fixed(int* ptr = &F) { *ptr = 42; } } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseExe); var result = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @"47"); var expectedIL = @" { // Code size 162 (0xa2) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, int V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__2.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003f IL_000a: ldc.i4.2 IL_000b: call ""System.Threading.Tasks.Task<int> Program.GetT<int>(int)"" IL_0010: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0015: stloc.2 IL_0016: ldloca.s V_2 IL_0018: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001d: brtrue.s IL_005b IL_001f: ldarg.0 IL_0020: ldc.i4.0 IL_0021: dup IL_0022: stloc.0 IL_0023: stfld ""int Program.<Test>d__2.<>1__state"" IL_0028: ldarg.0 IL_0029: ldloc.2 IL_002a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_002f: ldarg.0 IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_0035: ldloca.s V_2 IL_0037: ldarg.0 IL_0038: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<Test>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<Test>d__2)"" IL_003d: leave.s IL_00a1 IL_003f: ldarg.0 IL_0040: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_0045: stloc.2 IL_0046: ldarg.0 IL_0047: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<Test>d__2.<>u__1"" IL_004c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0052: ldarg.0 IL_0053: ldc.i4.m1 IL_0054: dup IL_0055: stloc.0 IL_0056: stfld ""int Program.<Test>d__2.<>1__state"" IL_005b: ldloca.s V_2 IL_005d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0062: stloc.1 IL_0063: ldsflda ""int Program.F"" IL_0068: ldloca.s V_1 IL_006a: ldc.i4.3 IL_006b: stloc.3 IL_006c: ldloca.s V_3 IL_006e: call ""void Program.M1(in int, in int, in int)"" IL_0073: leave.s IL_008e } catch System.Exception { IL_0075: stloc.s V_4 IL_0077: ldarg.0 IL_0078: ldc.i4.s -2 IL_007a: stfld ""int Program.<Test>d__2.<>1__state"" IL_007f: ldarg.0 IL_0080: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_0085: ldloc.s V_4 IL_0087: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008c: leave.s IL_00a1 } IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<Test>d__2.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__2.<>t__builder"" IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a1: ret } "; result.VerifyIL("Program.<Test>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", expectedIL); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); result = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @"47"); result.VerifyIL("Program.<Test>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", expectedIL); } [Fact] public void InParamAsyncSpill2() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { M1(await GetT(1), await GetT(2), 3); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3) { System.Console.WriteLine(arg1 + arg2 + arg3); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"6"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillMethods() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f M1(GetLocal(ref local).f, 42, GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of calls M1(GetLocal(ref local).f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillMethodsWriteable() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f M1(GetLocalWriteable(ref local).f, 42, GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of calls M1(GetLocalWriteable(ref local).f, await GetT(42), GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); } private static ref S1 GetLocalWriteable(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3"); } [WorkItem(20764, "https://github.com/dotnet/roslyn/issues/20764")] [Fact] public void InParamAsyncSpillStructField() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling M1(local.f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] public void InParamAsyncSpillClassField() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling M1(local.f, await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } public static void M1(in int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public class S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] public void InParamAsyncSpillExtension() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // prints 2 42 2 2 note aliasing for all arguments regardless of spilling local.f.M1(await GetT(42), GetLocalWriteable(ref local).f, GetLocalWriteable(ref local).f); } private static ref S1 GetLocalWriteable(ref S1 local) { local.f++; return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } static class Ext { public static void M1(in this int arg1, in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(arg1); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } public struct S1 { public int f; } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 2 42 2 2"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamAsyncSpillReadOnlyStructThis() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static async Task Test() { var local = new S1(); // BASELINE - without an await // prints 3 42 3 3 note the aliasing, 3 is the last state of the local.f GetLocal(ref local).M1( 42, GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of a call GetLocal(ref local).M1(await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); local = new S1(); // prints 1 42 3 3 note no aliasing for the first argument because of spilling of a call GetLocalWriteable(ref local).M1(await GetT(42), GetLocal(ref local).f, GetLocal(ref local).f); } private static ref readonly S1 GetLocal(ref S1 local) { local = new S1(local.f + 1); return ref local; } private static ref S1 GetLocalWriteable(ref S1 local) { local = new S1(local.f + 1); return ref local; } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } public readonly struct S1 { public readonly int f; public S1(int val) { this.f = val; } public void M1(in int arg2, in int arg3, in int arg4) { System.Console.WriteLine(this.f); System.Console.WriteLine(arg2); System.Console.WriteLine(arg3); System.Console.WriteLine(arg4); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 3 3 1 42 3 3 1 42 3 3"); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 3 42 2 3 1 42 2 3 1 42 2 3"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InParamAsyncSpillReadOnlyStructThis_NoValCapture() { var text = @" using System.Threading.Tasks; class Program { static void Main(string[] args) { Test().Wait(); } public static readonly S1 s1 = new S1(1); public static readonly S1 s2 = new S1(2); public static readonly S1 s3 = new S1(3); public static readonly S1 s4 = new S1(4); public static async Task Test() { s1.M1(s2, await GetT(s3), s4); } public static async Task<T> GetT<T>(T val) { await Task.Yield(); return val; } } public readonly struct S1 { public readonly int f; public S1(int val) { this.f = val; } public void M1(in S1 arg2, in S1 arg3, in S1 arg4) { System.Console.WriteLine(this.f); System.Console.WriteLine(arg2.f); System.Console.WriteLine(arg3.f); System.Console.WriteLine(arg4.f); } } "; var comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: @" 1 2 3 4"); // NOTE: s1, s3 and s4 are all directly loaded via ldsflda and not spilled. v.VerifyIL("Program.<Test>d__5.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 170 (0xaa) .maxstack 4 .locals init (int V_0, S1 V_1, System.Runtime.CompilerServices.TaskAwaiter<S1> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__5.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldsfld ""S1 Program.s3"" IL_000f: call ""System.Threading.Tasks.Task<S1> Program.GetT<S1>(S1)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<S1> System.Threading.Tasks.Task<S1>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<S1>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Test>d__5.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<S1>, Program.<Test>d__5>(ref System.Runtime.CompilerServices.TaskAwaiter<S1>, ref Program.<Test>d__5)"" IL_0041: leave.s IL_00a9 IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<S1>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Test>d__5.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""S1 System.Runtime.CompilerServices.TaskAwaiter<S1>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsflda ""S1 Program.s1"" IL_006c: ldsflda ""S1 Program.s2"" IL_0071: ldloca.s V_1 IL_0073: ldsflda ""S1 Program.s4"" IL_0078: call ""void S1.M1(in S1, in S1, in S1)"" IL_007d: leave.s IL_0096 } catch System.Exception { IL_007f: stloc.3 IL_0080: ldarg.0 IL_0081: ldc.i4.s -2 IL_0083: stfld ""int Program.<Test>d__5.<>1__state"" IL_0088: ldarg.0 IL_0089: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_008e: ldloc.3 IL_008f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0094: leave.s IL_00a9 } IL_0096: ldarg.0 IL_0097: ldc.i4.s -2 IL_0099: stfld ""int Program.<Test>d__5.<>1__state"" IL_009e: ldarg.0 IL_009f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_00a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a9: ret } "); comp = CreateCompilationWithMscorlib46(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); v = CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @" 1 2 3 4"); // NOTE: s1, s3 and s4 are all directly loaded via ldsflda and not spilled. v.VerifyIL("Program.<Test>d__5.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 183 (0xb7) .maxstack 4 .locals init (int V_0, S1 V_1, System.Runtime.CompilerServices.TaskAwaiter<S1> V_2, S1 V_3, S1 V_4, S1 V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__5.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0043 IL_000a: ldsfld ""S1 Program.s3"" IL_000f: call ""System.Threading.Tasks.Task<S1> Program.GetT<S1>(S1)"" IL_0014: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<S1> System.Threading.Tasks.Task<S1>.GetAwaiter()"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: call ""bool System.Runtime.CompilerServices.TaskAwaiter<S1>.IsCompleted.get"" IL_0021: brtrue.s IL_005f IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: dup IL_0026: stloc.0 IL_0027: stfld ""int Program.<Test>d__5.<>1__state"" IL_002c: ldarg.0 IL_002d: ldloc.2 IL_002e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0033: ldarg.0 IL_0034: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_0039: ldloca.s V_2 IL_003b: ldarg.0 IL_003c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<S1>, Program.<Test>d__5>(ref System.Runtime.CompilerServices.TaskAwaiter<S1>, ref Program.<Test>d__5)"" IL_0041: leave.s IL_00b6 IL_0043: ldarg.0 IL_0044: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0049: stloc.2 IL_004a: ldarg.0 IL_004b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<S1> Program.<Test>d__5.<>u__1"" IL_0050: initobj ""System.Runtime.CompilerServices.TaskAwaiter<S1>"" IL_0056: ldarg.0 IL_0057: ldc.i4.m1 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<Test>d__5.<>1__state"" IL_005f: ldloca.s V_2 IL_0061: call ""S1 System.Runtime.CompilerServices.TaskAwaiter<S1>.GetResult()"" IL_0066: stloc.1 IL_0067: ldsfld ""S1 Program.s1"" IL_006c: stloc.3 IL_006d: ldloca.s V_3 IL_006f: ldsfld ""S1 Program.s2"" IL_0074: stloc.s V_4 IL_0076: ldloca.s V_4 IL_0078: ldloca.s V_1 IL_007a: ldsfld ""S1 Program.s4"" IL_007f: stloc.s V_5 IL_0081: ldloca.s V_5 IL_0083: call ""void S1.M1(in S1, in S1, in S1)"" IL_0088: leave.s IL_00a3 } catch System.Exception { IL_008a: stloc.s V_6 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Program.<Test>d__5.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_009a: ldloc.s V_6 IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a1: leave.s IL_00b6 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Program.<Test>d__5.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Test>d__5.<>t__builder"" IL_00b1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b6: ret } "); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10834")] public void InParamGenericReadonly() { var text = @" class Program { static void Main(string[] args) { var o = new D(); var s = new S1(); o.M1(s); // should not be mutated. System.Console.WriteLine(s.field); } } abstract class C<U> { public abstract void M1<T>(in T arg) where T : U, I1; } class D: C<S1> { public override void M1<T>(in T arg) { arg.M3(); } } public struct S1: I1 { public int field; public void M3() { field = 42; } } interface I1 { void M3(); } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"0"); comp.VerifyIL("D.M1<T>(in T)", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldobj ""T"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I1.M3()"" IL_0014: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10834")] public void InParamGenericReadonlyROstruct() { var text = @" class Program { static void Main(string[] args) { var o = new D(); var s = new S1(); o.M1(s); } } abstract class C<U> { public abstract void M1<T>(in T arg) where T : U, I1; } class D: C<S1> { public override void M1<T>(in T arg) { arg.M3(); } } public readonly struct S1: I1 { public void M3() { } } interface I1 { void M3(); } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @""); comp.VerifyIL("D.M1<T>(in T)", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldobj ""T"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I1.M3()"" IL_0014: ret }"); } [Fact] public void RefReadOnlyOptionalParameters() { CompileAndVerify(@" using System; class Program { static void Print(in int p = 5) { Console.Write(p); } static void Main() { Print(); Console.Write(""-""); Print(9); } }", expectedOutput: "5-9"); } [WorkItem(23338, "https://github.com/dotnet/roslyn/issues/23338")] [Fact] public void InParamsNullable() { var text = @" class Program { static void Main(string[] args) { S1 s = new S1(); s.val = 42; S1? ns = s; Test1(in ns); Test2(ref ns); } static void Test1(in S1? arg) { // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); // should not mutate arg.ToString(); // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); } static void Test2(ref S1? arg) { // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); // can mutate arg.ToString(); // cannot not mutate System.Console.Write(arg.GetValueOrDefault()); } } struct S1 { public int val; public override string ToString() { var result = val.ToString(); val = 0; return result; } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242420"); comp.VerifyIL("Program.Test1(in S1?)", @" { // Code size 54 (0x36) .maxstack 1 .locals init (S1? V_0) IL_0000: ldarg.0 IL_0001: call ""S1 S1?.GetValueOrDefault()"" IL_0006: box ""S1"" IL_000b: call ""void System.Console.Write(object)"" IL_0010: ldarg.0 IL_0011: ldobj ""S1?"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: constrained. ""S1?"" IL_001f: callvirt ""string object.ToString()"" IL_0024: pop IL_0025: ldarg.0 IL_0026: call ""S1 S1?.GetValueOrDefault()"" IL_002b: box ""S1"" IL_0030: call ""void System.Console.Write(object)"" IL_0035: ret }"); comp.VerifyIL("Program.Test2(ref S1?)", @" { // Code size 46 (0x2e) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""S1 S1?.GetValueOrDefault()"" IL_0006: box ""S1"" IL_000b: call ""void System.Console.Write(object)"" IL_0010: ldarg.0 IL_0011: constrained. ""S1?"" IL_0017: callvirt ""string object.ToString()"" IL_001c: pop IL_001d: ldarg.0 IL_001e: call ""S1 S1?.GetValueOrDefault()"" IL_0023: box ""S1"" IL_0028: call ""void System.Console.Write(object)"" IL_002d: ret }"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(in Test a, in Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary_Right() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(Test a, in Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Binary_Left() { var reference = CreateCompilation(@" public class Test { public int Value { get; set; } public static int operator +(in Test a, Test b) { return a.Value + b.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = 3 }; var b = new Test { Value = 6 }; System.Console.WriteLine(a + b); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "9"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "9"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Unary() { var reference = CreateCompilation(@" public class Test { public bool Value { get; set; } public static bool operator !(in Test a) { return !a.Value; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = true }; System.Console.WriteLine(!a); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "False"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "False"); } [Fact] [WorkItem(530136, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=530136")] public void OperatorsWithInParametersFromMetadata_Conversion() { var reference = CreateCompilation(@" public class Test { public bool Value { get; set; } public static explicit operator int(in Test a) { return a.Value ? 3 : 5; } }"); var code = @" class Program { static void Main(string[] args) { var a = new Test { Value = true }; System.Console.WriteLine((int)a); } }"; CompileAndVerify(code, references: new[] { reference.ToMetadataReference() }, expectedOutput: "3"); CompileAndVerify(code, references: new[] { reference.EmitToImageReference() }, expectedOutput: "3"); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_NoArgs() { var code = @" class Program { static void Test(in int value = 5) { System.Console.WriteLine(value); } static void Main(string[] args) { /*<bind>*/Test()/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "5").VerifyIL("Program.Main", @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""void Program.Test(in int)"" IL_0009: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test()') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_OneArg() { var code = @" class Program { static void Test(in int value = 5) { System.Console.WriteLine(value); } static void Main(string[] args) { /*<bind>*/Test(10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "10").VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""void Program.Test(in int)"" IL_000a: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(10)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_NoArgs() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test()/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(1, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: value1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'Test()') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test()') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_OneArg() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(2)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(2, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(2)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test(2)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test(2)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Optional_Optional_TwoArgs() { var code = @" class Program { static void Test(in int value1 = 1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(3, 10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(3, 10)").VerifyIL("Program.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 10 IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void Program.Test(in int, in int)"" IL_000e: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test([in System.Int32 value1 = 1], [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(3, 10)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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: value2) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Required_Optional_OneArg() { var code = @" class Program { static void Test(in int value1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(1)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(1, 5)").VerifyIL("Program.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.5 IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""void Program.Test(in int, in int)"" IL_000d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test(in System.Int32 value1, [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.DefaultValue, Matching Parameter: value2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Test(1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: 'Test(1)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_Method_Required_Optional_TwoArgs() { var code = @" class Program { static void Test(in int value1, in int value2 = 5) { System.Console.WriteLine($""({value1}, {value2})""); } static void Main(string[] args) { /*<bind>*/Test(2, 10)/*<bind>*/; } }"; CompileAndVerify(code, expectedOutput: "(2, 10)").VerifyIL("Program.Main", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 10 IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void Program.Test(in int, in int)"" IL_000e: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.Test(in System.Int32 value1, [in System.Int32 value2 = 5])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test(2, 10)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value1) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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: value2) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Optional_Optional_OneArg() { var code = @" class Program { public int this[in int p1 = 1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[3]/*<bind>*/ += 10; } }"; CompileAndVerify(code, expectedOutput: @" get p1=3 p2=2 set p1=3 p2=2 to 10 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.3 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.3 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.2 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 10 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[[in System.Int32 p1 = 1], [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[3]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'obj[3]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'obj[3]') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Optional_Optional_TwoArgs() { var code = @" class Program { public int this[in int p1 = 1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[4, 5]/*<bind>*/ += 11; } }"; CompileAndVerify(code, expectedOutput: @" get p1=4 p2=5 set p1=4 p2=5 to 11 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.4 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.5 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.4 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.5 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 11 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[[in System.Int32 p1 = 1], [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[4, 5]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '4') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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: p2) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Required_Optional_OneArg() { var code = @" class Program { public int this[in int p1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[3]/*<bind>*/ += 10; } }"; CompileAndVerify(code, expectedOutput: @" get p1=3 p2=2 set p1=3 p2=2 to 10 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.3 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.3 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.2 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 10 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[in System.Int32 p1, [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[3]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'obj[3]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'obj[3]') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void OptionalInParameters_CompoundAssignment_Required_Optional_TwoArgs() { var code = @" class Program { public int this[in int p1, in int p2 = 2] { get { System.Console.WriteLine($""get p1={p1} p2={p2}""); return 0; } set { System.Console.WriteLine($""set p1={p1} p2={p2} to {value}""); } } static void Main(string[] args) { var obj = new Program(); /*<bind>*/obj[4, 5]/*<bind>*/ += 11; } }"; CompileAndVerify(code, expectedOutput: @" get p1=4 p2=5 set p1=4 p2=5 to 11 ").VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 6 .locals init (Program V_0, int V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.4 IL_0008: stloc.1 IL_0009: ldloca.s V_1 IL_000b: ldc.i4.5 IL_000c: stloc.2 IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: ldc.i4.4 IL_0011: stloc.3 IL_0012: ldloca.s V_3 IL_0014: ldc.i4.5 IL_0015: stloc.s V_4 IL_0017: ldloca.s V_4 IL_0019: callvirt ""int Program.this[in int, in int].get"" IL_001e: ldc.i4.s 11 IL_0020: add IL_0021: callvirt ""void Program.this[in int, in int].set"" IL_0026: ret }"); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(code, @" IPropertyReferenceOperation: System.Int32 Program.this[in System.Int32 p1, [in System.Int32 p2 = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'obj[4, 5]') Instance Receiver: ILocalReferenceOperation: obj (OperationKind.LocalReference, Type: Program) (Syntax: 'obj') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: '4') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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: p2) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void Issue23691_PassingInOptionalArgumentsByRef_OneArg() { var code = @" class Program { static void Main() { /*<bind>*/A(1)/*<bind>*/; } static void A(in double x = 1, in string y = ""test"") => System.Console.WriteLine(y); static void B(in float x, in float y, in float z = 3.0f) => System.Console.WriteLine(x * y * z); }"; CompileAndVerify(code, expectedOutput: "test").VerifyIL("Program.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (double V_0, string V_1) IL_0000: ldc.r8 1 IL_0009: stloc.0 IL_000a: ldloca.s V_0 IL_000c: ldstr ""test"" IL_0011: stloc.1 IL_0012: ldloca.s V_1 IL_0014: call ""void Program.A(in double, in string)"" IL_0019: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.A([in System.Double x = 1], [in System.String y = ""test""])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'A(1)') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"", IsImplicit) (Syntax: 'A(1)') 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)", DiagnosticDescription.None); } [Fact] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.ReadOnlyReferences)] [WorkItem(23691, "https://github.com/dotnet/roslyn/issues/23691")] public void Issue23691_PassingInOptionalArgumentsByRef_TwoArgs() { var code = @" class Program { static void Main() { /*<bind>*/B(1, 2)/*<bind>*/; } static void A(in double x = 1, in string y = ""test"") => System.Console.WriteLine(y); static void B(in float x, in float y, in float z = 3.0f) => System.Console.WriteLine(x * y * z); }"; CompileAndVerify(code, expectedOutput: "6").VerifyIL("Program.Main", @" { // Code size 30 (0x1e) .maxstack 3 .locals init (float V_0, float V_1, float V_2) IL_0000: ldc.r4 1 IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: ldc.r4 2 IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldc.r4 3 IL_0015: stloc.2 IL_0016: ldloca.s V_2 IL_0018: call ""void Program.B(in float, in float, in float)"" IL_001d: ret }"); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(code, @" IInvocationOperation (void Program.B(in System.Single x, in System.Single y, [in System.Single z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'B(1, 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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.DefaultValue, Matching Parameter: z) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'B(1, 2)') ILiteralOperation (OperationKind.Literal, Type: System.Single, Constant: 3, IsImplicit) (Syntax: 'B(1, 2)') 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)", DiagnosticDescription.None); } [WorkItem(23692, "https://github.com/dotnet/roslyn/issues/23692")] [Fact] public void ThisToInParam() { var code = @" using System; static class Ex { public static void InMethod(in X arg) => Console.Write(arg); } class X { public void M() { // pass `this` by in-parameter. Ex.InMethod(this); } } class Program { static void Main() { var x = new X(); // baseline Ex.InMethod(x); x.M(); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "XX"); verifier.VerifyIL("X.M()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""void Ex.InMethod(in X)"" IL_0007: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_Local() { var code = @" using System; public class Test { static void Main(string[] args) { int x = 50; Moo(x + 0, () => x = 60); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 41 (0x29) .maxstack 3 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.s 50 IL_0009: stfld ""int Test.<>c__DisplayClass0_0.x"" IL_000e: ldloc.0 IL_000f: ldfld ""int Test.<>c__DisplayClass0_0.x"" IL_0014: stloc.1 IL_0015: ldloca.s V_1 IL_0017: ldloc.0 IL_0018: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_001e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0023: call ""void Test.Moo(in int, System.Action)"" IL_0028: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ArrayAccess() { var code = @" using System; public class Test { static void Main(string[] args) { int[] x = new int[] { 50 }; Moo(x[0] + 0, () => x[0] = 60); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 52 (0x34) .maxstack 5 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 50 IL_0011: stelem.i4 IL_0012: stfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_0017: ldloc.0 IL_0018: ldfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_001d: ldc.i4.0 IL_001e: ldelem.i4 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: call ""void Test.Moo(in int, System.Action)"" IL_0033: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ArrayAccessReordered() { var code = @" using System; public class Test { static void Main(string[] args) { int[] x = new int[] { 50 }; Moo(change: () => x[0] = 60, y: x[0] + 0); } static void Moo(in int y, Action change) { Console.Write(y); change(); Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "5050"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 52 (0x34) .maxstack 5 .locals init (Test.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 50 IL_0011: stelem.i4 IL_0012: stfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_0017: ldloc.0 IL_0018: ldfld ""int[] Test.<>c__DisplayClass0_0.x"" IL_001d: ldc.i4.0 IL_001e: ldelem.i4 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldftn ""void Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: call ""void Test.Moo(in int, System.Action)"" IL_0033: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_FieldAcces() { var code = @" using System; public class Test { struct S1 { public int x; } static S1 s = new S1 { x = 555 }; static void Main(string[] args) { Moo(s.x + 0); } static void Moo(in int y) { Console.Write(y); s.x = 123; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "555555"); verifier.VerifyIL("Test.Main(string[])", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int V_0) IL_0000: ldsflda ""Test.S1 Test.s"" IL_0005: ldfld ""int Test.S1.x"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: call ""void Test.Moo(in int)"" IL_0012: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_RoFieldAcces() { var code = @" using System; public class Test { struct S1 { public int x; } readonly S1 s; static void Main(string[] args) { var x = new Test(); } public Test() { Test1(s.x + 0, ref s.x); } private void Test1(in int y, ref int f) { Console.Write(y); f = 1; Console.Write(y); Test2(s.x + 0, ref f); } private void Test2(in int y, ref int f) { Console.Write(y); f = 2; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "0011", verify: Verification.Fails); verifier.VerifyIL("Test..ctor()", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: ldflda ""Test.S1 Test.s"" IL_000d: ldfld ""int Test.S1.x"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: ldarg.0 IL_0016: ldflda ""Test.S1 Test.s"" IL_001b: ldflda ""int Test.S1.x"" IL_0020: call ""void Test.Test1(in int, ref int)"" IL_0025: ret } "); verifier.VerifyIL("Test.Test1(in int, ref int)", @" { // Code size 39 (0x27) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldind.i4 IL_0002: call ""void System.Console.Write(int)"" IL_0007: ldarg.2 IL_0008: ldc.i4.1 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldind.i4 IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldarg.0 IL_0013: ldflda ""Test.S1 Test.s"" IL_0018: ldfld ""int Test.S1.x"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: ldarg.2 IL_0021: call ""void Test.Test2(in int, ref int)"" IL_0026: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_ThisAcces() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } public Test() { Test3(null ?? this); } private void Test3(in Test y) { } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: ""); verifier.VerifyIL("Test..ctor()", @" { // Code size 17 (0x11) .maxstack 2 .locals init (Test V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: stloc.0 IL_0009: ldloca.s V_0 IL_000b: call ""void Test.Test3(in Test)"" IL_0010: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_RefMethod() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } private string s = ""hi""; private ref string M1() { return ref s; } public Test() { Test3(null ?? M1()); } private void Test3(in string y) { Console.Write(y); s = ""bye""; Console.Write(y); } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "hihi"); verifier.VerifyIL("Test..ctor()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: ldstr ""hi"" IL_0006: stfld ""string Test.s"" IL_000b: ldarg.0 IL_000c: call ""object..ctor()"" IL_0011: ldarg.0 IL_0012: ldarg.0 IL_0013: call ""ref string Test.M1()"" IL_0018: ldind.ref IL_0019: stloc.0 IL_001a: ldloca.s V_0 IL_001c: call ""void Test.Test3(in string)"" IL_0021: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperator() { var code = @" using System; public class Test { static void Main(string[] args) { var x = new Test(); } private static string s = ""hi""; public Test() { var dummy = (null ?? s) + this; } public static string operator +(in string y, in Test t) { Console.Write(y); s = ""bye""; Console.Write(y); return y; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "hihi"); verifier.VerifyIL("Test..ctor()", @" { // Code size 23 (0x17) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldsfld ""string Test.s"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldarga.s V_0 IL_0010: call ""string Test.op_Addition(in string, in Test)"" IL_0015: pop IL_0016: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperatorLifted() { var code = @" using System; public struct Test { static void Main(string[] args) { var x = new Test(); x.Test1(); } private Action change; public Test(Action change) { this.change = change; } public void Test1() { int s = 1; Test? t = new Test(() => s = 42); var dummy = s + t; } public static int operator +(in int y, in Test t) { Console.Write(y); t.change(); Console.Write(y); return 88; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "11"); verifier.VerifyIL("Test.Test1()", @" { // Code size 71 (0x47) .maxstack 2 .locals init (Test.<>c__DisplayClass3_0 V_0, //CS$<>8__locals0 int V_1, Test? V_2, Test V_3) IL_0000: newobj ""Test.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld ""int Test.<>c__DisplayClass3_0.s"" IL_000d: ldloc.0 IL_000e: ldftn ""void Test.<>c__DisplayClass3_0.<Test1>b__0()"" IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0019: newobj ""Test..ctor(System.Action)"" IL_001e: newobj ""Test?..ctor(Test)"" IL_0023: ldloc.0 IL_0024: ldfld ""int Test.<>c__DisplayClass3_0.s"" IL_0029: stloc.1 IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: call ""bool Test?.HasValue.get"" IL_0032: brfalse.s IL_0046 IL_0034: ldloca.s V_1 IL_0036: ldloca.s V_2 IL_0038: call ""Test Test?.GetValueOrDefault()"" IL_003d: stloc.3 IL_003e: ldloca.s V_3 IL_0040: call ""int Test.op_Addition(in int, in Test)"" IL_0045: pop IL_0046: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InOperatorUnary() { var code = @" using System; public class Test { static void Main(string[] args) { Test1(); } private static Test s = new Test(); public static void Test1() { var dummy = +(null ?? s); } public static Test operator +(in Test y) { Console.Write(y); s = default; Console.Write(y); return y; } } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "TestTest"); verifier.VerifyIL("Test.Test1()", @" { // Code size 15 (0xf) .maxstack 1 .locals init (Test V_0) IL_0000: ldsfld ""Test Test.s"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""Test Test.op_UnaryPlus(in Test)"" IL_000d: pop IL_000e: ret } "); } [WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] [Fact] public void OptimizedRValueToIn_InConversion() { var code = @" using System; public class Test { static void Main(string[] args) { Test1(); } private static Test s = new Test(); public static void Test1() { int dummyI = (null ?? s); s = new Derived(); long dummyL = (null ?? s); } public static implicit operator int(in Test y) { Console.Write(y.ToString()); s = default; Console.Write(y.ToString()); return 1; } } class Derived : Test { } "; var compilation = CreateCompilation(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "TestTestDerivedDerived"); verifier.VerifyIL("Test.Test1()", @" { // Code size 39 (0x27) .maxstack 1 .locals init (Test V_0) IL_0000: ldsfld ""Test Test.s"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""int Test.op_Implicit(in Test)"" IL_000d: pop IL_000e: newobj ""Derived..ctor()"" IL_0013: stsfld ""Test Test.s"" IL_0018: ldsfld ""Test Test.s"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: call ""int Test.op_Implicit(in Test)"" IL_0025: pop IL_0026: ret } "); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the DiagnosticAnalyzer ("Analysis") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override void DiagnosticAnalyzerInitialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression); protected override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption2<ExpressionBodyPreference> option) { var declaration = (LambdaExpressionSyntax)context.Node; var diagnostic = AnalyzeSyntax(context.SemanticModel, option, declaration, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic AnalyzeSyntax( SemanticModel semanticModel, CodeStyleOption2<ExpressionBodyPreference> option, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { if (CanOfferUseExpressionBody(option.Value, declaration)) { var location = GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty; return DiagnosticHelper.Create( CreateDescriptorWithId(UseExpressionBodyTitle, UseExpressionBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } if (CanOfferUseBlockBody(semanticModel, option.Value, declaration, cancellationToken)) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = GetDiagnosticLocation(declaration); var properties = ImmutableDictionary<string, string>.Empty; var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(UseBlockBodyTitle, UseBlockBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } return null; } private static Location GetDiagnosticLocation(LambdaExpressionSyntax declaration) => Location.Create(declaration.SyntaxTree, TextSpan.FromBounds(declaration.SpanStart, declaration.ArrowToken.Span.End)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the DiagnosticAnalyzer ("Analysis") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override void DiagnosticAnalyzerInitialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression); protected override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption2<ExpressionBodyPreference> option) { var declaration = (LambdaExpressionSyntax)context.Node; var diagnostic = AnalyzeSyntax(context.SemanticModel, option, declaration, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic AnalyzeSyntax( SemanticModel semanticModel, CodeStyleOption2<ExpressionBodyPreference> option, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { if (CanOfferUseExpressionBody(option.Value, declaration)) { var location = GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty; return DiagnosticHelper.Create( CreateDescriptorWithId(UseExpressionBodyTitle, UseExpressionBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } if (CanOfferUseBlockBody(semanticModel, option.Value, declaration, cancellationToken)) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = GetDiagnosticLocation(declaration); var properties = ImmutableDictionary<string, string>.Empty; var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(UseBlockBodyTitle, UseBlockBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } return null; } private static Location GetDiagnosticLocation(LambdaExpressionSyntax declaration) => Location.Create(declaration.SyntaxTree, TextSpan.FromBounds(declaration.SpanStart, declaration.ArrowToken.Span.End)); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/Extensibility/NavigationBar/INavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarItemService : ILanguageService { Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextSnapshot textSnapshot, CancellationToken cancellationToken); bool ShowItemGrayedIfNear(NavigationBarItem item); /// <summary> /// Returns <see langword="true"/> if navigation (or generation) happened. <see langword="false"/> otherwise. /// </summary> Task<bool> TryNavigateToItemAsync(Document document, NavigationBarItem item, ITextView view, ITextSnapshot textSnapshot, 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; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarItemService : ILanguageService { Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextSnapshot textSnapshot, CancellationToken cancellationToken); bool ShowItemGrayedIfNear(NavigationBarItem item); /// <summary> /// Returns <see langword="true"/> if navigation (or generation) happened. <see langword="false"/> otherwise. /// </summary> Task<bool> TryNavigateToItemAsync(Document document, NavigationBarItem item, ITextView view, ITextSnapshot textSnapshot, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.EventSymbolKey.cs
// Licensed to the .NET Foundation under one or more 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 { internal partial struct SymbolKey { private static class EventSymbolKey { public static void Create(IEventSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } using var result = GetMembersOfNamedType<IEventSymbol>(containingTypeResolution, metadataName); return CreateResolution(result, $"({nameof(EventSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class EventSymbolKey { public static void Create(IEventSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } using var result = GetMembersOfNamedType<IEventSymbol>(containingTypeResolution, metadataName); return CreateResolution(result, $"({nameof(EventSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/TestUtilities/Utilities/TestFixtureHelper`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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal sealed class TestFixtureHelper<TFixture> where TFixture : class, IDisposable, new() { private readonly object _gate = new(); /// <summary> /// Holds a weak reference to the current test fixture instance. This reference allows /// <see cref="GetOrCreateFixture"/> to access and add a reference to the current test fixture if one exists, /// but does not prevent the fixture from being disposed after the last reference to it is released. /// </summary> private ReferenceCountedDisposable<TFixture>.WeakReference _weakFixture; /// <summary> /// Gets a reference to a test fixture, or creates it if one does not already exist. /// </summary> /// <remarks> /// <para>The resulting test fixture will not be disposed until the last referencer disposes of its reference. /// It is possible for more than one test fixture to be created during the life of any single test, but only one /// test fixture will be live at any given point.</para> /// /// <para>The following shows how a block of test code can ensure a single test fixture is created and used /// within any given block of code:</para> /// /// <code> /// using (var fixture = GetOrCreateFixture()) /// { /// // The test fixture 'fixture' is guaranteed to not be released or replaced within this block /// } /// </code> /// </remarks> /// <returns>The test fixture instance.</returns> internal ReferenceCountedDisposable<TFixture> GetOrCreateFixture() { lock (_gate) { if (_weakFixture.TryAddReference() is { } fixture) return fixture; var result = new ReferenceCountedDisposable<TFixture>(new TFixture()); _weakFixture = new ReferenceCountedDisposable<TFixture>.WeakReference(result); return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal sealed class TestFixtureHelper<TFixture> where TFixture : class, IDisposable, new() { private readonly object _gate = new(); /// <summary> /// Holds a weak reference to the current test fixture instance. This reference allows /// <see cref="GetOrCreateFixture"/> to access and add a reference to the current test fixture if one exists, /// but does not prevent the fixture from being disposed after the last reference to it is released. /// </summary> private ReferenceCountedDisposable<TFixture>.WeakReference _weakFixture; /// <summary> /// Gets a reference to a test fixture, or creates it if one does not already exist. /// </summary> /// <remarks> /// <para>The resulting test fixture will not be disposed until the last referencer disposes of its reference. /// It is possible for more than one test fixture to be created during the life of any single test, but only one /// test fixture will be live at any given point.</para> /// /// <para>The following shows how a block of test code can ensure a single test fixture is created and used /// within any given block of code:</para> /// /// <code> /// using (var fixture = GetOrCreateFixture()) /// { /// // The test fixture 'fixture' is guaranteed to not be released or replaced within this block /// } /// </code> /// </remarks> /// <returns>The test fixture instance.</returns> internal ReferenceCountedDisposable<TFixture> GetOrCreateFixture() { lock (_gate) { if (_weakFixture.TryAddReference() is { } fixture) return fixture; var result = new ReferenceCountedDisposable<TFixture>(new TFixture()); _weakFixture = new ReferenceCountedDisposable<TFixture>.WeakReference(result); return result; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax Parenthesize( this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) { // a 'ref' expression should never be parenthesized. It fundamentally breaks the code. // This is because, from the language's perspective there is no such thing as a ref // expression. instead, there are constructs like ```return ref expr``` or // ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the // ref's do not belong to the exprs, but instead belong to the parent construct. i.e. // ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For // parsing convenience, and to prevent having to update all these constructs, we settled // on a ref-expression node. But this node isn't a true expression that be operated // on like with everything else. if (expression.IsKind(SyntaxKind.RefExpression)) { return expression; } // Throw expressions are not permitted to be parenthesized: // // "a" ?? throw new ArgumentNullException() // // is legal whereas // // "a" ?? (throw new ArgumentNullException()) // // is not. if (expression.IsKind(SyntaxKind.ThrowExpression)) { return expression; } var result = ParenthesizeWorker(expression, includeElasticTrivia); return addSimplifierAnnotation ? result.WithAdditionalAnnotations(Simplifier.Annotation) : result; } private static ExpressionSyntax ParenthesizeWorker( this ExpressionSyntax expression, bool includeElasticTrivia) { var withoutTrivia = expression.WithoutTrivia(); var parenthesized = includeElasticTrivia ? SyntaxFactory.ParenthesizedExpression(withoutTrivia) : SyntaxFactory.ParenthesizedExpression( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); return parenthesized.WithTriviaFrom(expression); } public static PatternSyntax Parenthesize( this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) { var withoutTrivia = pattern.WithoutTrivia(); var parenthesized = includeElasticTrivia ? SyntaxFactory.ParenthesizedPattern(withoutTrivia) : SyntaxFactory.ParenthesizedPattern( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); var result = parenthesized.WithTriviaFrom(pattern); return addSimplifierAnnotation ? result.WithAdditionalAnnotations(Simplifier.Annotation) : result; } public static CastExpressionSyntax Cast( this ExpressionSyntax expression, ITypeSymbol targetType) { var parenthesized = expression.Parenthesize(); var castExpression = SyntaxFactory.CastExpression( targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized); return castExpression.WithAdditionalAnnotations(Simplifier.Annotation); } /// <summary> /// Adds to <paramref name="targetType"/> if it does not contain an anonymous /// type and binds to the same type at the given <paramref name="position"/>. /// </summary> public static ExpressionSyntax CastIfPossible( this ExpressionSyntax expression, ITypeSymbol targetType, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { if (targetType.ContainsAnonymousType()) { return expression; } if (targetType.Kind == SymbolKind.DynamicType) { targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object); } var typeSyntax = targetType.GenerateTypeSyntax(); var type = semanticModel.GetSpeculativeTypeInfo( position, typeSyntax, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (!targetType.Equals(type)) { return expression; } var castExpression = expression.Cast(targetType); // Ensure that inserting the cast doesn't change the semantics. var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken); var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel; if (speculativeSemanticModel == null) { return expression; } var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression; if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken)) { return expression; } return castExpression; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax Parenthesize( this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) { // a 'ref' expression should never be parenthesized. It fundamentally breaks the code. // This is because, from the language's perspective there is no such thing as a ref // expression. instead, there are constructs like ```return ref expr``` or // ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the // ref's do not belong to the exprs, but instead belong to the parent construct. i.e. // ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For // parsing convenience, and to prevent having to update all these constructs, we settled // on a ref-expression node. But this node isn't a true expression that be operated // on like with everything else. if (expression.IsKind(SyntaxKind.RefExpression)) { return expression; } // Throw expressions are not permitted to be parenthesized: // // "a" ?? throw new ArgumentNullException() // // is legal whereas // // "a" ?? (throw new ArgumentNullException()) // // is not. if (expression.IsKind(SyntaxKind.ThrowExpression)) { return expression; } var result = ParenthesizeWorker(expression, includeElasticTrivia); return addSimplifierAnnotation ? result.WithAdditionalAnnotations(Simplifier.Annotation) : result; } private static ExpressionSyntax ParenthesizeWorker( this ExpressionSyntax expression, bool includeElasticTrivia) { var withoutTrivia = expression.WithoutTrivia(); var parenthesized = includeElasticTrivia ? SyntaxFactory.ParenthesizedExpression(withoutTrivia) : SyntaxFactory.ParenthesizedExpression( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); return parenthesized.WithTriviaFrom(expression); } public static PatternSyntax Parenthesize( this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) { var withoutTrivia = pattern.WithoutTrivia(); var parenthesized = includeElasticTrivia ? SyntaxFactory.ParenthesizedPattern(withoutTrivia) : SyntaxFactory.ParenthesizedPattern( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); var result = parenthesized.WithTriviaFrom(pattern); return addSimplifierAnnotation ? result.WithAdditionalAnnotations(Simplifier.Annotation) : result; } public static CastExpressionSyntax Cast( this ExpressionSyntax expression, ITypeSymbol targetType) { var parenthesized = expression.Parenthesize(); var castExpression = SyntaxFactory.CastExpression( targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized); return castExpression.WithAdditionalAnnotations(Simplifier.Annotation); } /// <summary> /// Adds to <paramref name="targetType"/> if it does not contain an anonymous /// type and binds to the same type at the given <paramref name="position"/>. /// </summary> public static ExpressionSyntax CastIfPossible( this ExpressionSyntax expression, ITypeSymbol targetType, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { if (targetType.ContainsAnonymousType()) { return expression; } if (targetType.Kind == SymbolKind.DynamicType) { targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object); } var typeSyntax = targetType.GenerateTypeSyntax(); var type = semanticModel.GetSpeculativeTypeInfo( position, typeSyntax, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (!targetType.Equals(type)) { return expression; } var castExpression = expression.Cast(targetType); // Ensure that inserting the cast doesn't change the semantics. var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken); var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel; if (speculativeSemanticModel == null) { return expression; } var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression; if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken)) { return expression; } return castExpression; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractExtensionMethodImportCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractExtensionMethodImportCompletionProvider : AbstractImportCompletionProvider { private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected abstract string GenericSuffix { get; } protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsRightOfNameSeparator && IsAddingImportsSupported(completionContext.Document); protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfExtensionMethodImportCompletionItem(); protected override async Task AddCompletionItemsAsync( CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespaceInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var syntaxFacts = completionContext.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol)) { using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); var inferredTypes = IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Document.Project.Solution.Workspace) ? syntaxContext.InferredTypes : ImmutableArray<ITypeSymbol>.Empty; var getItemsTask = Task.Run(() => ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync( completionContext.Document, completionContext.Position, receiverTypeSymbol, namespaceInScope, inferredTypes, forceIndexCreation: isExpandedCompletion, linkedTokenSource.Token)); var timeoutInMilliseconds = completionContext.Options.GetOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion); // Timebox is enabled if timeout value is >= 0 and we are not triggered via expander if (timeoutInMilliseconds >= 0 && !isExpandedCompletion) { // timeout == 0 means immediate timeout (for testing purpose) if (timeoutInMilliseconds == 0 || await Task.WhenAny(getItemsTask, Task.Delay(timeoutInMilliseconds, linkedTokenSource.Token)).ConfigureAwait(false) != getItemsTask) { nestedTokenSource.Cancel(); CompletionProvidersLogger.LogExtensionMethodCompletionTimeoutCount(); return; } } // Either the timebox is not enabled, so we need to wait until the operation for complete, // or there's no timeout, and we now have all completion items ready. var items = await getItemsTask.ConfigureAwait(false); var receiverTypeKey = SymbolKey.CreateString(receiverTypeSymbol, cancellationToken); completionContext.AddItems(items.Select(i => Convert(i, receiverTypeKey))); } else { // If we can't get a valid receiver type, then we don't show expander as available. // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside // `ShouldProvideCompletion` method above, which is intended for quick syntax based check. completionContext.ExpandItemsAvailable = false; } } } private bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } private static bool TryGetReceiverTypeSymbol( SyntaxContext syntaxContext, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken, [NotNullWhen(true)] out ITypeSymbol? receiverTypeSymbol) { var parentNode = syntaxContext.TargetToken.Parent; // Even though implicit access to extension method is allowed, we decide not support it for simplicity // e.g. we will not provide completion for unimported extension method in this case // New Bar() {.X = .$$ } var expressionNode = syntaxFacts.GetLeftSideOfDot(parentNode, allowImplicitTarget: false); if (expressionNode != null) { // Check if we are accessing members of a type, no extension methods are exposed off of types. if (syntaxContext.SemanticModel.GetSymbolInfo(expressionNode, cancellationToken).GetAnySymbol() is not ITypeSymbol) { // The expression we're calling off of needs to have an actual instance type. // We try to be more tolerant to errors here so completion would still be available in certain case of partially typed code. receiverTypeSymbol = syntaxContext.SemanticModel.GetTypeInfo(expressionNode, cancellationToken).Type; if (receiverTypeSymbol is IErrorTypeSymbol errorTypeSymbol) { receiverTypeSymbol = errorTypeSymbol.CandidateSymbols.Select(s => GetSymbolType(s)).FirstOrDefault(s => s != null); } return receiverTypeSymbol != null; } } receiverTypeSymbol = null; return false; } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol switch { ILocalSymbol localSymbol => localSymbol.Type, IFieldSymbol fieldSymbol => fieldSymbol.Type, IPropertySymbol propertySymbol => propertySymbol.Type, IParameterSymbol parameterSymbol => parameterSymbol.Type, IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol, _ => symbol as ITypeSymbol, }; private CompletionItem Convert(SerializableImportCompletionItem serializableItem, string receiverTypeSymbolKey) => ImportCompletionItem.Create( serializableItem.Name, serializableItem.Arity, serializableItem.ContainingNamespace, serializableItem.Glyph, GenericSuffix, CompletionItemFlags.Expanded, (serializableItem.SymbolKeyData, receiverTypeSymbolKey, serializableItem.AdditionalOverloadCount), serializableItem.IncludedInTargetTypeCompletion); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractExtensionMethodImportCompletionProvider : AbstractImportCompletionProvider { private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected abstract string GenericSuffix { get; } protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsRightOfNameSeparator && IsAddingImportsSupported(completionContext.Document); protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfExtensionMethodImportCompletionItem(); protected override async Task AddCompletionItemsAsync( CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespaceInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var syntaxFacts = completionContext.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol)) { using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); var inferredTypes = IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Document.Project.Solution.Workspace) ? syntaxContext.InferredTypes : ImmutableArray<ITypeSymbol>.Empty; var getItemsTask = Task.Run(() => ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync( completionContext.Document, completionContext.Position, receiverTypeSymbol, namespaceInScope, inferredTypes, forceIndexCreation: isExpandedCompletion, linkedTokenSource.Token)); var timeoutInMilliseconds = completionContext.Options.GetOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion); // Timebox is enabled if timeout value is >= 0 and we are not triggered via expander if (timeoutInMilliseconds >= 0 && !isExpandedCompletion) { // timeout == 0 means immediate timeout (for testing purpose) if (timeoutInMilliseconds == 0 || await Task.WhenAny(getItemsTask, Task.Delay(timeoutInMilliseconds, linkedTokenSource.Token)).ConfigureAwait(false) != getItemsTask) { nestedTokenSource.Cancel(); CompletionProvidersLogger.LogExtensionMethodCompletionTimeoutCount(); return; } } // Either the timebox is not enabled, so we need to wait until the operation for complete, // or there's no timeout, and we now have all completion items ready. var items = await getItemsTask.ConfigureAwait(false); var receiverTypeKey = SymbolKey.CreateString(receiverTypeSymbol, cancellationToken); completionContext.AddItems(items.Select(i => Convert(i, receiverTypeKey))); } else { // If we can't get a valid receiver type, then we don't show expander as available. // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside // `ShouldProvideCompletion` method above, which is intended for quick syntax based check. completionContext.ExpandItemsAvailable = false; } } } private bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } private static bool TryGetReceiverTypeSymbol( SyntaxContext syntaxContext, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken, [NotNullWhen(true)] out ITypeSymbol? receiverTypeSymbol) { var parentNode = syntaxContext.TargetToken.Parent; // Even though implicit access to extension method is allowed, we decide not support it for simplicity // e.g. we will not provide completion for unimported extension method in this case // New Bar() {.X = .$$ } var expressionNode = syntaxFacts.GetLeftSideOfDot(parentNode, allowImplicitTarget: false); if (expressionNode != null) { // Check if we are accessing members of a type, no extension methods are exposed off of types. if (syntaxContext.SemanticModel.GetSymbolInfo(expressionNode, cancellationToken).GetAnySymbol() is not ITypeSymbol) { // The expression we're calling off of needs to have an actual instance type. // We try to be more tolerant to errors here so completion would still be available in certain case of partially typed code. receiverTypeSymbol = syntaxContext.SemanticModel.GetTypeInfo(expressionNode, cancellationToken).Type; if (receiverTypeSymbol is IErrorTypeSymbol errorTypeSymbol) { receiverTypeSymbol = errorTypeSymbol.CandidateSymbols.Select(s => GetSymbolType(s)).FirstOrDefault(s => s != null); } return receiverTypeSymbol != null; } } receiverTypeSymbol = null; return false; } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol switch { ILocalSymbol localSymbol => localSymbol.Type, IFieldSymbol fieldSymbol => fieldSymbol.Type, IPropertySymbol propertySymbol => propertySymbol.Type, IParameterSymbol parameterSymbol => parameterSymbol.Type, IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol, _ => symbol as ITypeSymbol, }; private CompletionItem Convert(SerializableImportCompletionItem serializableItem, string receiverTypeSymbolKey) => ImportCompletionItem.Create( serializableItem.Name, serializableItem.Arity, serializableItem.ContainingNamespace, serializableItem.Glyph, GenericSuffix, CompletionItemFlags.Expanded, (serializableItem.SymbolKeyData, receiverTypeSymbolKey, serializableItem.AdditionalOverloadCount), serializableItem.IncludedInTargetTypeCompletion); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class FunctionPointerParameterSymbol : ParameterSymbol { private readonly FunctionPointerMethodSymbol _containingSymbol; public FunctionPointerParameterSymbol(TypeWithAnnotations typeWithAnnotations, RefKind refKind, int ordinal, FunctionPointerMethodSymbol containingSymbol, ImmutableArray<CustomModifier> refCustomModifiers) { TypeWithAnnotations = typeWithAnnotations; RefKind = refKind; Ordinal = ordinal; _containingSymbol = containingSymbol; RefCustomModifiers = refCustomModifiers; } public override TypeWithAnnotations TypeWithAnnotations { get; } public override RefKind RefKind { get; } public override int Ordinal { get; } public override Symbol ContainingSymbol => _containingSymbol; public override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } if (!(other is FunctionPointerParameterSymbol param)) { return false; } return Equals(param, compareKind); } internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => other.Ordinal == Ordinal && _containingSymbol.Equals(other._containingSymbol, compareKind); internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal + 1); } internal int MethodHashCode() => Hash.Combine(TypeWithAnnotations.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()); public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsDiscard => false; public override bool IsParams => false; public override bool IsImplicitlyDeclared => true; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; internal override bool IsMetadataOptional => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; internal override ConstantValue? ExplicitDefaultConstantValue => null; internal override bool IsIDispatchConstant => false; internal override bool IsIUnknownConstant => false; internal override bool IsCallerFilePath => false; internal override bool IsCallerLineNumber => false; internal override bool IsCallerMemberName => false; internal override int CallerArgumentExpressionParameterIndex => -1; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => 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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class FunctionPointerParameterSymbol : ParameterSymbol { private readonly FunctionPointerMethodSymbol _containingSymbol; public FunctionPointerParameterSymbol(TypeWithAnnotations typeWithAnnotations, RefKind refKind, int ordinal, FunctionPointerMethodSymbol containingSymbol, ImmutableArray<CustomModifier> refCustomModifiers) { TypeWithAnnotations = typeWithAnnotations; RefKind = refKind; Ordinal = ordinal; _containingSymbol = containingSymbol; RefCustomModifiers = refCustomModifiers; } public override TypeWithAnnotations TypeWithAnnotations { get; } public override RefKind RefKind { get; } public override int Ordinal { get; } public override Symbol ContainingSymbol => _containingSymbol; public override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } if (!(other is FunctionPointerParameterSymbol param)) { return false; } return Equals(param, compareKind); } internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => other.Ordinal == Ordinal && _containingSymbol.Equals(other._containingSymbol, compareKind); internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal + 1); } internal int MethodHashCode() => Hash.Combine(TypeWithAnnotations.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()); public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsDiscard => false; public override bool IsParams => false; public override bool IsImplicitlyDeclared => true; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; internal override bool IsMetadataOptional => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; internal override ConstantValue? ExplicitDefaultConstantValue => null; internal override bool IsIDispatchConstant => false; internal override bool IsIUnknownConstant => false; internal override bool IsCallerFilePath => false; internal override bool IsCallerLineNumber => false; internal override bool IsCallerMemberName => false; internal override int CallerArgumentExpressionParameterIndex => -1; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Rename/RenameRewriterParameters.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Rename.ConflictEngine; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal class RenameRewriterParameters { internal readonly CancellationToken CancellationToken; internal readonly ISet<TextSpan> ConflictLocationSpans; internal readonly RenameOptionSet OptionSet; internal readonly Solution OriginalSolution; internal readonly SyntaxTree OriginalSyntaxTree; internal readonly string OriginalText; internal readonly ICollection<string> PossibleNameConflicts; internal readonly RenameAnnotation RenamedSymbolDeclarationAnnotation; internal readonly Dictionary<TextSpan, RenameLocation> RenameLocations; internal readonly RenamedSpansTracker RenameSpansTracker; internal readonly ISymbol RenameSymbol; internal readonly string ReplacementText; internal readonly bool ReplacementTextValid; internal readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> StringAndCommentTextSpans; internal readonly SyntaxNode SyntaxRoot; internal readonly Document Document; internal readonly SemanticModel SemanticModel; internal readonly AnnotationTable<RenameAnnotation> RenameAnnotations; public RenameRewriterParameters( RenameAnnotation renamedSymbolDeclarationAnnotation, Document document, SemanticModel semanticModel, SyntaxNode syntaxRoot, string replacementText, string originalText, ICollection<string> possibleNameConflicts, Dictionary<TextSpan, RenameLocation> renameLocations, ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> stringAndCommentTextSpans, ISet<TextSpan> conflictLocationSpans, Solution originalSolution, ISymbol renameSymbol, bool replacementTextValid, RenamedSpansTracker renameSpansTracker, RenameOptionSet optionSet, AnnotationTable<RenameAnnotation> renameAnnotations, CancellationToken cancellationToken) { this.RenamedSymbolDeclarationAnnotation = renamedSymbolDeclarationAnnotation; this.Document = document; this.SemanticModel = semanticModel; this.SyntaxRoot = syntaxRoot; this.OriginalSyntaxTree = semanticModel.SyntaxTree; this.ReplacementText = replacementText; this.OriginalText = originalText; this.PossibleNameConflicts = possibleNameConflicts; this.RenameLocations = renameLocations; this.StringAndCommentTextSpans = stringAndCommentTextSpans; this.ConflictLocationSpans = conflictLocationSpans; this.OriginalSolution = originalSolution; this.RenameSymbol = renameSymbol; this.ReplacementTextValid = replacementTextValid; this.CancellationToken = cancellationToken; this.RenameSpansTracker = renameSpansTracker; this.OptionSet = optionSet; this.RenameAnnotations = renameAnnotations; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Rename.ConflictEngine; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal class RenameRewriterParameters { internal readonly CancellationToken CancellationToken; internal readonly ISet<TextSpan> ConflictLocationSpans; internal readonly RenameOptionSet OptionSet; internal readonly Solution OriginalSolution; internal readonly SyntaxTree OriginalSyntaxTree; internal readonly string OriginalText; internal readonly ICollection<string> PossibleNameConflicts; internal readonly RenameAnnotation RenamedSymbolDeclarationAnnotation; internal readonly Dictionary<TextSpan, RenameLocation> RenameLocations; internal readonly RenamedSpansTracker RenameSpansTracker; internal readonly ISymbol RenameSymbol; internal readonly string ReplacementText; internal readonly bool ReplacementTextValid; internal readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> StringAndCommentTextSpans; internal readonly SyntaxNode SyntaxRoot; internal readonly Document Document; internal readonly SemanticModel SemanticModel; internal readonly AnnotationTable<RenameAnnotation> RenameAnnotations; public RenameRewriterParameters( RenameAnnotation renamedSymbolDeclarationAnnotation, Document document, SemanticModel semanticModel, SyntaxNode syntaxRoot, string replacementText, string originalText, ICollection<string> possibleNameConflicts, Dictionary<TextSpan, RenameLocation> renameLocations, ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> stringAndCommentTextSpans, ISet<TextSpan> conflictLocationSpans, Solution originalSolution, ISymbol renameSymbol, bool replacementTextValid, RenamedSpansTracker renameSpansTracker, RenameOptionSet optionSet, AnnotationTable<RenameAnnotation> renameAnnotations, CancellationToken cancellationToken) { this.RenamedSymbolDeclarationAnnotation = renamedSymbolDeclarationAnnotation; this.Document = document; this.SemanticModel = semanticModel; this.SyntaxRoot = syntaxRoot; this.OriginalSyntaxTree = semanticModel.SyntaxTree; this.ReplacementText = replacementText; this.OriginalText = originalText; this.PossibleNameConflicts = possibleNameConflicts; this.RenameLocations = renameLocations; this.StringAndCommentTextSpans = stringAndCommentTextSpans; this.ConflictLocationSpans = conflictLocationSpans; this.OriginalSolution = originalSolution; this.RenameSymbol = renameSymbol; this.ReplacementTextValid = replacementTextValid; this.CancellationToken = cancellationToken; this.RenameSpansTracker = renameSpansTracker; this.OptionSet = optionSet; this.RenameAnnotations = renameAnnotations; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Workspace/WorkspaceChangeKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public enum WorkspaceChangeKind { /// <summary> /// The current solution changed for an unspecified reason. /// </summary> SolutionChanged = 0, /// <summary> /// A solution was added to the workspace. /// </summary> SolutionAdded = 1, /// <summary> /// The current solution was removed from the workspace. /// </summary> SolutionRemoved = 2, /// <summary> /// The current solution was cleared of all projects and documents. /// </summary> SolutionCleared = 3, /// <summary> /// The current solution was reloaded. /// </summary> SolutionReloaded = 4, /// <summary> /// A project was added to the current solution. /// </summary> ProjectAdded = 5, /// <summary> /// A project was removed from the current solution. /// </summary> ProjectRemoved = 6, /// <summary> /// A project in the current solution was changed. /// </summary> ProjectChanged = 7, /// <summary> /// A project in the current solution was reloaded. /// </summary> ProjectReloaded = 8, /// <summary> /// A document was added to the current solution. /// </summary> DocumentAdded = 9, /// <summary> /// A document was removed from the current solution. /// </summary> DocumentRemoved = 10, /// <summary> /// A document in the current solution was reloaded. /// </summary> DocumentReloaded = 11, /// <summary> /// A document in the current solution was changed. /// </summary> /// <remarks> /// When linked files are edited, one <see cref="DocumentChanged"/> event is fired per /// linked file. All of these events contain the same OldSolution, and they all contain /// the same NewSolution. This is so that we can trigger document change events on all /// affected documents without reporting intermediate states in which the linked file /// contents do not match. Each <see cref="DocumentChanged"/> event does not represent /// an incremental update from the previous event in this special case. /// </remarks> DocumentChanged = 12, /// <summary> /// An additional document was added to the current solution. /// </summary> AdditionalDocumentAdded = 13, /// <summary> /// An additional document was removed from the current solution. /// </summary> AdditionalDocumentRemoved = 14, /// <summary> /// An additional document in the current solution was reloaded. /// </summary> AdditionalDocumentReloaded = 15, /// <summary> /// An additional document in the current solution was changed. /// </summary> AdditionalDocumentChanged = 16, /// <summary> /// The document in the current solution had is info changed; name, folders, filepath /// </summary> DocumentInfoChanged = 17, /// <summary> /// An analyzer config document was added to the current solution. /// </summary> AnalyzerConfigDocumentAdded = 18, /// <summary> /// An analyzer config document was removed from the current solution. /// </summary> AnalyzerConfigDocumentRemoved = 19, /// <summary> /// An analyzer config document in the current solution was reloaded. /// </summary> AnalyzerConfigDocumentReloaded = 20, /// <summary> /// An analyzer config document in the current solution was changed. /// </summary> AnalyzerConfigDocumentChanged = 21, } internal static class WorkspaceChangeKindExtensions { public static bool IsValid(this WorkspaceChangeKind kind) => kind >= WorkspaceChangeKind.SolutionChanged && kind <= WorkspaceChangeKind.AnalyzerConfigDocumentChanged; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public enum WorkspaceChangeKind { /// <summary> /// The current solution changed for an unspecified reason. /// </summary> SolutionChanged = 0, /// <summary> /// A solution was added to the workspace. /// </summary> SolutionAdded = 1, /// <summary> /// The current solution was removed from the workspace. /// </summary> SolutionRemoved = 2, /// <summary> /// The current solution was cleared of all projects and documents. /// </summary> SolutionCleared = 3, /// <summary> /// The current solution was reloaded. /// </summary> SolutionReloaded = 4, /// <summary> /// A project was added to the current solution. /// </summary> ProjectAdded = 5, /// <summary> /// A project was removed from the current solution. /// </summary> ProjectRemoved = 6, /// <summary> /// A project in the current solution was changed. /// </summary> ProjectChanged = 7, /// <summary> /// A project in the current solution was reloaded. /// </summary> ProjectReloaded = 8, /// <summary> /// A document was added to the current solution. /// </summary> DocumentAdded = 9, /// <summary> /// A document was removed from the current solution. /// </summary> DocumentRemoved = 10, /// <summary> /// A document in the current solution was reloaded. /// </summary> DocumentReloaded = 11, /// <summary> /// A document in the current solution was changed. /// </summary> /// <remarks> /// When linked files are edited, one <see cref="DocumentChanged"/> event is fired per /// linked file. All of these events contain the same OldSolution, and they all contain /// the same NewSolution. This is so that we can trigger document change events on all /// affected documents without reporting intermediate states in which the linked file /// contents do not match. Each <see cref="DocumentChanged"/> event does not represent /// an incremental update from the previous event in this special case. /// </remarks> DocumentChanged = 12, /// <summary> /// An additional document was added to the current solution. /// </summary> AdditionalDocumentAdded = 13, /// <summary> /// An additional document was removed from the current solution. /// </summary> AdditionalDocumentRemoved = 14, /// <summary> /// An additional document in the current solution was reloaded. /// </summary> AdditionalDocumentReloaded = 15, /// <summary> /// An additional document in the current solution was changed. /// </summary> AdditionalDocumentChanged = 16, /// <summary> /// The document in the current solution had is info changed; name, folders, filepath /// </summary> DocumentInfoChanged = 17, /// <summary> /// An analyzer config document was added to the current solution. /// </summary> AnalyzerConfigDocumentAdded = 18, /// <summary> /// An analyzer config document was removed from the current solution. /// </summary> AnalyzerConfigDocumentRemoved = 19, /// <summary> /// An analyzer config document in the current solution was reloaded. /// </summary> AnalyzerConfigDocumentReloaded = 20, /// <summary> /// An analyzer config document in the current solution was changed. /// </summary> AnalyzerConfigDocumentChanged = 21, } internal static class WorkspaceChangeKindExtensions { public static bool IsValid(this WorkspaceChangeKind kind) => kind >= WorkspaceChangeKind.SolutionChanged && kind <= WorkspaceChangeKind.AnalyzerConfigDocumentChanged; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/WinRT/Metadata/WinMdMetadataTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Unit tests for programs that use the Windows.winmd file. // // Checks to see that types are forwarded correctly, that // metadata files are loaded as they should, etc. public class WinMdMetadataTests : CSharpTestBase { /// <summary> /// Make sure that the members of a function are forwarded to their appropriate types. /// We do this by checking that the first parameter of /// Windows.UI.Text.ITextRange.SetPoint(Point p...) gets forwarded to the /// System.Runtime.WindowsRuntime assembly. /// </summary> [Fact] public void FunctionSignatureForwarded() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Text"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("ITextRange"); var func = itextrange.GetMember<PEMethodSymbol>("SetPoint"); var pt = ((PEParameterSymbol)(func.Parameters[0])).Type as PENamedTypeSymbol; Assert.Equal("System.Runtime.WindowsRuntime", pt.ContainingAssembly.Name); } /// <summary> /// Make sure that a delegate defined in Windows.winmd has a public constructor /// (by default, all delegates in Windows.winmd have a private constructor). /// </summary> [Fact] public void DelegateConstructorMarkedPublic() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Xaml"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("SuspendingEventHandler"); var func = itextrange.GetMember<PEMethodSymbol>(".ctor"); Assert.Equal(Accessibility.Public, func.DeclaredAccessibility); } /// <summary> /// Verify that Windows.Foundation.Uri forwards successfully /// to System.Uri /// </summary> [Fact] public void TypeForwardingRenaming() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("Foundation"); var iref = wns1.GetMember<PENamedTypeSymbol>("IUriRuntimeClass"); var func = iref.GetMember<PEMethodSymbol>("CombineUri"); var ret = func.ReturnTypeWithAnnotations; Assert.Equal("System.Uri", func.ReturnType.ToTestDisplayString()); } /// <summary> /// Verify that WinMd types are marked as private so that the /// C# developer cannot instantiate them. /// </summary> [Fact] public void WinMdTypesDefPrivate() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Foundation"); var clas = wns2.GetMember<PENamedTypeSymbol>("Point"); Assert.Equal(Accessibility.Internal, clas.DeclaredAccessibility); } /// <summary> /// Verify that Windows.UI.Colors.Black is forwarded to the /// System.Runtime.WindowsRuntime.dll assembly. /// </summary> [Fact] public void WinMdColorType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("UI"); var clas = wns2.GetMember<TypeSymbol>("Colors"); var blk = clas.GetMembers("Black").Single(); //The windows.winmd module points to a Windows.UI.Color which should be modified to belong //to System.Runtime.WindowsRuntime Assert.Equal("System.Runtime.WindowsRuntime.dll", ((PENamedTypeSymbol)((((PropertySymbol)(blk)).GetMethod).ReturnType)).ContainingModule.ToString()); } /// <summary> /// Ensure that a simple program that uses projected types can compile /// and run. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void WinMdColorTest() { var text = @"using Windows.UI; using Windows.Foundation; public class A{ public static void Main(){ var a = Colors.Black; System.Console.WriteLine(a.ToString()); } };"; CompileAndVerify(text, WinRtRefs, targetFramework: TargetFramework.Empty, expectedOutput: "#FF000000"); } /// <summary> /// Test that the metadata adapter correctly projects IReference to INullable /// </summary> [Fact] public void IReferenceToINullableType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Globalization"); var wns3 = wns2.GetMember<NamespaceSymbol>("NumberFormatting"); var clas = wns3.GetMember<TypeSymbol>("DecimalFormatter"); var puint = clas.GetMembers("ParseUInt").Single(); // The return type of ParseUInt should be Nullable<ulong>, not IReference<ulong> Assert.Equal("ulong?", ((Microsoft.CodeAnalysis.CSharp.Symbols.ConstructedNamedTypeSymbol) (((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)puint).ReturnType)).ToString()); } /// <summary> /// Test that a program projects IReference to INullable. /// </summary> [Fact] public void WinMdIReferenceINullableTest() { var source = @"using System; using Windows.Globalization.NumberFormatting; public class C { public static void Main(string[] args) { var format = new DecimalFormatter(); ulong result = format.ParseUInt(""10"") ?? 0; Console.WriteLine(result); result = format.ParseUInt(""-1"") ?? 0; Console.WriteLine(result); } }"; var verifier = this.CompileAndVerifyOnWin8Only(source, expectedOutput: "10\r\n0"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")] public void WinMdAssemblyQualifiedType() { var source = @"using System; [MyAttribute(typeof(C1))] public class C { public static void Main(string[] args) { } } public class MyAttribute : System.Attribute { public MyAttribute(System.Type type) { } } "; CompileAndVerify( source, WinRtRefs.Concat(new[] { AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference() }), targetFramework: TargetFramework.Empty, symbolValidator: m => { var module = (PEModuleSymbol)m; var c = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMember("C"); var attributeHandle = module.Module.MetadataReader.GetCustomAttributes(c.Handle).Single(); string value; module.Module.TryExtractStringValueFromAttribute(attributeHandle, out value); Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Unit tests for programs that use the Windows.winmd file. // // Checks to see that types are forwarded correctly, that // metadata files are loaded as they should, etc. public class WinMdMetadataTests : CSharpTestBase { /// <summary> /// Make sure that the members of a function are forwarded to their appropriate types. /// We do this by checking that the first parameter of /// Windows.UI.Text.ITextRange.SetPoint(Point p...) gets forwarded to the /// System.Runtime.WindowsRuntime assembly. /// </summary> [Fact] public void FunctionSignatureForwarded() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Text"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("ITextRange"); var func = itextrange.GetMember<PEMethodSymbol>("SetPoint"); var pt = ((PEParameterSymbol)(func.Parameters[0])).Type as PENamedTypeSymbol; Assert.Equal("System.Runtime.WindowsRuntime", pt.ContainingAssembly.Name); } /// <summary> /// Make sure that a delegate defined in Windows.winmd has a public constructor /// (by default, all delegates in Windows.winmd have a private constructor). /// </summary> [Fact] public void DelegateConstructorMarkedPublic() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Xaml"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("SuspendingEventHandler"); var func = itextrange.GetMember<PEMethodSymbol>(".ctor"); Assert.Equal(Accessibility.Public, func.DeclaredAccessibility); } /// <summary> /// Verify that Windows.Foundation.Uri forwards successfully /// to System.Uri /// </summary> [Fact] public void TypeForwardingRenaming() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("Foundation"); var iref = wns1.GetMember<PENamedTypeSymbol>("IUriRuntimeClass"); var func = iref.GetMember<PEMethodSymbol>("CombineUri"); var ret = func.ReturnTypeWithAnnotations; Assert.Equal("System.Uri", func.ReturnType.ToTestDisplayString()); } /// <summary> /// Verify that WinMd types are marked as private so that the /// C# developer cannot instantiate them. /// </summary> [Fact] public void WinMdTypesDefPrivate() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Foundation"); var clas = wns2.GetMember<PENamedTypeSymbol>("Point"); Assert.Equal(Accessibility.Internal, clas.DeclaredAccessibility); } /// <summary> /// Verify that Windows.UI.Colors.Black is forwarded to the /// System.Runtime.WindowsRuntime.dll assembly. /// </summary> [Fact] public void WinMdColorType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("UI"); var clas = wns2.GetMember<TypeSymbol>("Colors"); var blk = clas.GetMembers("Black").Single(); //The windows.winmd module points to a Windows.UI.Color which should be modified to belong //to System.Runtime.WindowsRuntime Assert.Equal("System.Runtime.WindowsRuntime.dll", ((PENamedTypeSymbol)((((PropertySymbol)(blk)).GetMethod).ReturnType)).ContainingModule.ToString()); } /// <summary> /// Ensure that a simple program that uses projected types can compile /// and run. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void WinMdColorTest() { var text = @"using Windows.UI; using Windows.Foundation; public class A{ public static void Main(){ var a = Colors.Black; System.Console.WriteLine(a.ToString()); } };"; CompileAndVerify(text, WinRtRefs, targetFramework: TargetFramework.Empty, expectedOutput: "#FF000000"); } /// <summary> /// Test that the metadata adapter correctly projects IReference to INullable /// </summary> [Fact] public void IReferenceToINullableType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Globalization"); var wns3 = wns2.GetMember<NamespaceSymbol>("NumberFormatting"); var clas = wns3.GetMember<TypeSymbol>("DecimalFormatter"); var puint = clas.GetMembers("ParseUInt").Single(); // The return type of ParseUInt should be Nullable<ulong>, not IReference<ulong> Assert.Equal("ulong?", ((Microsoft.CodeAnalysis.CSharp.Symbols.ConstructedNamedTypeSymbol) (((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)puint).ReturnType)).ToString()); } /// <summary> /// Test that a program projects IReference to INullable. /// </summary> [Fact] public void WinMdIReferenceINullableTest() { var source = @"using System; using Windows.Globalization.NumberFormatting; public class C { public static void Main(string[] args) { var format = new DecimalFormatter(); ulong result = format.ParseUInt(""10"") ?? 0; Console.WriteLine(result); result = format.ParseUInt(""-1"") ?? 0; Console.WriteLine(result); } }"; var verifier = this.CompileAndVerifyOnWin8Only(source, expectedOutput: "10\r\n0"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")] public void WinMdAssemblyQualifiedType() { var source = @"using System; [MyAttribute(typeof(C1))] public class C { public static void Main(string[] args) { } } public class MyAttribute : System.Attribute { public MyAttribute(System.Type type) { } } "; CompileAndVerify( source, WinRtRefs.Concat(new[] { AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference() }), targetFramework: TargetFramework.Empty, symbolValidator: m => { var module = (PEModuleSymbol)m; var c = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMember("C"); var attributeHandle = module.Module.MetadataReader.GetCustomAttributes(c.Handle).Single(); string value; module.Module.TryExtractStringValueFromAttribute(attributeHandle, out value); Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value); }); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { public class DeclarationNameCompletionProviderTests : AbstractCSharpCompletionProviderTests { private const string Span = @" namespace System { public readonly ref struct Span<T> { private readonly T[] arr; public ref T this[int i] => ref arr[i]; public override int GetHashCode() => 1; public int Length { get; } unsafe public Span(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public Span(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { get => ref _span[_index]; } } public static implicit operator Span<T>(T[] array) => new Span<T>(array); public Span<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new Span<T>(copy); } } public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public ref readonly T this[int i] => ref arr[i]; public override int GetHashCode() => 2; public int Length { get; } unsafe public ReadOnlySpan(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly ReadOnlySpan<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref readonly T Current { get => ref _span[_index]; } } public static implicit operator ReadOnlySpan<T>(T[] array) => array == null ? default : new ReadOnlySpan<T>(array); public static implicit operator ReadOnlySpan<T>(string stringValue) => string.IsNullOrEmpty(stringValue) ? default : new ReadOnlySpan<T>((T[])(object)stringValue.ToCharArray()); public ReadOnlySpan<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new ReadOnlySpan<T>(copy); } } public readonly ref struct SpanLike<T> { public readonly Span<T> field; } public enum Color: sbyte { Red, Green, Blue } public static unsafe class Helpers { public static T[] ToArray<T>(void* ptr, int count) { if (ptr == null) { return null; } if (typeof(T) == typeof(int)) { var arr = new int[count]; for(int i = 0; i < count; i++) { arr[i] = ((int*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(byte)) { var arr = new byte[count]; for(int i = 0; i < count; i++) { arr[i] = ((byte*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(char)) { var arr = new char[count]; for(int i = 0; i < count; i++) { arr[i] = ((char*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(Color)) { var arr = new Color[count]; for(int i = 0; i < count; i++) { arr[i] = ((Color*)ptr)[i]; } return (T[])(object)arr; } throw new Exception(""add a case for: "" + typeof(T)); } } }"; private const string IAsyncEnumerable = @" namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Runtime.CompilerServices { using System.Threading.Tasks; public sealed class AsyncMethodBuilderAttribute : Attribute { public AsyncMethodBuilderAttribute(Type builderType) { } public Type BuilderType { get; } } public struct AsyncValueTaskMethodBuilder { public ValueTask Task => default; public static AsyncValueTaskMethodBuilder Create() => default; public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {} public void SetException(Exception exception) {} public void SetResult() {} public void SetStateMachine(IAsyncStateMachine stateMachine) {} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {} } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public void GetResult() { } public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public TResult GetResult() => default; public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } } namespace System.Threading.Tasks { using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable<ValueTask> { public ValueTask(Task task) {} public ValueTask(IValueTaskSource source, short token) {} public bool IsCompleted => default; public bool IsCompletedSuccessfully => default; public bool IsFaulted => default; public bool IsCanceled => default; public Task AsTask() => default; public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => default; public override bool Equals(object obj) => default; public bool Equals(ValueTask other) => default; public ValueTaskAwaiter GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask Preserve() => default; public static bool operator ==(ValueTask left, ValueTask right) => default; public static bool operator !=(ValueTask left, ValueTask right) => default; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { public ValueTask(TResult result) {} public ValueTask(Task<TResult> task) {} public ValueTask(IValueTaskSource<TResult> source, short token) {} public bool IsFaulted => default; public bool IsCompletedSuccessfully => default; public bool IsCompleted => default; public bool IsCanceled => default; public TResult Result => default; public Task<TResult> AsTask() => default; public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) => default; public bool Equals(ValueTask<TResult> other) => default; public override bool Equals(object obj) => default; public ValueTaskAwaiter<TResult> GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask<TResult> Preserve() => default; public override string ToString() => default; public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) => default; public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) => default; } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } }"; internal override Type GetCompletionProviderType() => typeof(DeclarationNameCompletionProvider); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48310, "https://github.com/dotnet/roslyn/issues/48310")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TreatRecordPositionalParameterAsProperty(string record) { var markup = $@" public class MyClass {{ }} public {record} R(MyClass $$ "; await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameWithOnlyType1() { var markup = @" public class MyClass { MyClass $$ } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.FieldPublic); await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic); await VerifyItemExistsAsync(markup, "GetMyClass", glyph: (int)Glyph.MethodPublic); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncTaskOfT() { var markup = @" using System.Threading.Tasks; public class C { async Task<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCAsync"); } [Fact(Skip = "not yet implemented"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task NonAsyncTaskOfT() { var markup = @" public class C { Task<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration1() { var markup = @" public class C { virtual C $$ } "; await VerifyItemExistsAsync(markup, "GetC"); await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "c"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking1() { var markup = @" using System.Threading; public class C { CancellationToken $$ } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking2() { var markup = @" interface I {} public class C { I $$ } "; await VerifyItemExistsAsync(markup, "GetI"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking3() { var markup = @" interface II {} public class C { II $$ } "; await VerifyItemExistsAsync(markup, "GetI"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking4() { var markup = @" interface IGoo {} public class C { IGoo $$ } "; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking5() { var markup = @" class SomeWonderfullyLongClassName {} public class C { SomeWonderfullyLongClassName $$ } "; await VerifyItemExistsAsync(markup, "Some"); await VerifyItemExistsAsync(markup, "SomeWonderfully"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLong"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLongClass"); await VerifyItemExistsAsync(markup, "Name"); await VerifyItemExistsAsync(markup, "ClassName"); await VerifyItemExistsAsync(markup, "LongClassName"); await VerifyItemExistsAsync(markup, "WonderfullyLongClassName"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLongClassName"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter1() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken $$ } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter2() { var markup = @" using System.Threading; public class C { void Goo(int x, CancellationToken c$$ } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter3() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter4() { var markup = @" using System.Threading; public class C { void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter5() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter6() { var markup = @" using System.Threading; void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter7() { var markup = @" using System.Threading; void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter8() { var markup = @" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken c$$] => throw null; } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter9() { var markup = @" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken cancellationToken, CancellationToken c$$] => throw null; } "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter10(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { void Goo(DbContext context) { void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter11(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { void Goo() { DbContext context; void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter12(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { DbContext dbContext; void Goo(DbContext context) { void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords1() { var markup = @" using System.Text; public class C { void Goo(StringBuilder $$) {} } "; await VerifyItemExistsAsync(markup, "stringBuilder", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "@string", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "builder", glyph: (int)Glyph.Parameter); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords2() { var markup = @" class For { } public class C { void Goo(For $$) {} } "; await VerifyItemExistsAsync(markup, "@for", glyph: (int)Glyph.Parameter); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords3() { var markup = @" class For { } public class C { void goo() { For $$ } } "; await VerifyItemExistsAsync(markup, "@for"); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords4() { var markup = @" using System.Text; public class C { void goo() { StringBuilder $$ } } "; await VerifyItemExistsAsync(markup, "stringBuilder"); await VerifyItemExistsAsync(markup, "@string"); await VerifyItemExistsAsync(markup, "builder"); } [WorkItem(25214, "https://github.com/dotnet/roslyn/issues/25214")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsLazyOfType1() { var markup = @" using System; using System.Collections.Generic; internal class Example { public Lazy<Item> $$ } public class Item { } "; await VerifyItemExistsAsync(markup, "item"); await VerifyItemExistsAsync(markup, "Item"); await VerifyItemExistsAsync(markup, "GetItem"); } [WorkItem(25214, "https://github.com/dotnet/roslyn/issues/25214")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsLazyOfType2() { var markup = @" using System; using System.Collections.Generic; internal class Example { public List<Lazy<Item>> $$ } public class Item { } "; await VerifyItemExistsAsync(markup, "items"); await VerifyItemExistsAsync(markup, "Items"); await VerifyItemExistsAsync(markup, "GetItems"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForInt() { var markup = @" using System.Threading; public class C { int $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForLong() { var markup = @" using System.Threading; public class C { long $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForDouble() { var markup = @" using System.Threading; public class C { double $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForFloat() { var markup = @" using System.Threading; public class C { float $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForSbyte() { var markup = @" using System.Threading; public class C { sbyte $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForShort() { var markup = @" using System.Threading; public class C { short $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForUint() { var markup = @" using System.Threading; public class C { uint $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForUlong() { var markup = @" using System.Threading; public class C { ulong $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestionsForUShort() { var markup = @" using System.Threading; public class C { ushort $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForBool() { var markup = @" using System.Threading; public class C { bool $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForByte() { var markup = @" using System.Threading; public class C { byte $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForChar() { var markup = @" using System.Threading; public class C { char $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForString() { var markup = @" public class C { string $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSingleLetterClassNameSuggested() { var markup = @" public class C { C $$ } "; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "c"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayElementTypeSuggested() { var markup = @" using System.Threading; public class MyClass { MyClass[] $$ } "; await VerifyItemExistsAsync(markup, "MyClasses"); await VerifyItemIsAbsentAsync(markup, "Array"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotTriggeredByVar() { var markup = @" public class C { var $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoid() { var markup = @" public class C { void $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterGeneric() { var markup = @" public class C { System.Collections.Generic.IEnumerable<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCs"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterVar() { var markup = @" public class C { void goo() { var $$ } } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCorrectOrder() { var markup = @" public class MyClass { MyClass $$ } "; var items = await GetCompletionItemsAsync(markup, SourceCodeKind.Regular); Assert.Equal( new[] { "myClass", "my", "@class", "MyClass", "My", "Class", "GetMyClass", "GetMy", "GetClass" }, items.Select(item => item.DisplayText)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDescriptionInsideClass() { var markup = @" public class MyClass { MyClass $$ } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.FieldPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "GetMyClass", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDescriptionInsideMethod() { var markup = @" public class MyClass { void M() { MyClass $$ } } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "MyClass"); await VerifyItemIsAbsentAsync(markup, "GetMyClass"); } [WorkItem(20273, "https://github.com/dotnet/roslyn/issues/20273")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Alias1() { var markup = @" using MyType = System.String; public class C { MyType $$ } "; await VerifyItemExistsAsync(markup, "my"); await VerifyItemExistsAsync(markup, "type"); await VerifyItemExistsAsync(markup, "myType"); } [WorkItem(20273, "https://github.com/dotnet/roslyn/issues/20273")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasWithInterfacePattern() { var markup = @" using IMyType = System.String; public class C { MyType $$ } "; await VerifyItemExistsAsync(markup, "my"); await VerifyItemExistsAsync(markup, "type"); await VerifyItemExistsAsync(markup, "myType"); } [WorkItem(20016, "https://github.com/dotnet/roslyn/issues/20016")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExistingName1() { var markup = @" using IMyType = System.String; public class C { MyType myType $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(20016, "https://github.com/dotnet/roslyn/issues/20016")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExistingName2() { var markup = @" using IMyType = System.String; public class C { MyType myType, MyType $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutVarArgument() { var markup = @" class Test { void Do(out Test goo) { Do(out var $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutArgument() { var markup = @" class Test { void Do(out Test goo) { Do(out Test $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutGenericArgument() { var markup = @" class Test { void Do<T>(out T goo) { Do(out Test $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration1() { var markup = @" class Test { void Do() { (System.Array array, System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration2() { var markup = @" class Test { void Do() { (array, action $$ } } "; await VerifyItemIsAbsentAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration_NestedTuples() { var markup = @" class Test { void Do() { ((int i1, int i2), (System.Array array, System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration_NestedTuples_CompletionInTheMiddle() { var markup = @" class Test { void Do() { ((System.Array array, System.Action $$), (int i1, int i2)) } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition1() { var markup = @" class Test { void Do() { (System.Array $$ } } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition2() { var markup = @" class Test { (System.Array $$) Test() => default; } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition3() { var markup = @" class Test { (System.Array array, System.Action $$) Test() => default; } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition4() { var markup = @" class Test { (System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition5() { var markup = @" class Test { void M((System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition_NestedTuples() { var markup = @" class Test { void M(((int, int), (int, System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition_InMiddleOfTuple() { var markup = @" class Test { void M((int, System.Array $$),int) } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementTypeInference() { var markup = @" class Test { void Do() { (var accessViolationException, var $$) = (new AccessViolationException(), new Action(() => { })); } } "; // Currently not supported: await VerifyItemIsAbsentAsync(markup, "action"); // see https://github.com/dotnet/roslyn/issues/27138 // after the issue ist fixed we expect this to work: // await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact(Skip = "Not yet supported"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementInGenericTypeArgument() { var markup = @" class Test { void Do() { System.Func<(System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementInvocationInsideTuple() { var markup = @" class Test { void Do() { int M(int i1, int i2) => i1; var t=(e1: 1, e2: M(1, $$)); } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize1() { var markup = @" using System.Collections.Generic; class Index { IEnumerable<Index> $$ } "; await VerifyItemExistsAsync(markup, "Indices"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize2() { var markup = @" using System.Collections.Generic; class Test { IEnumerable<IEnumerable<Test>> $$ } "; await VerifyItemExistsAsync(markup, "tests"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize3() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { IEnumerable<CancellationToken> $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeList() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { List<CancellationToken> $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeArray() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { CancellationToken[] $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeSpan() { var markup = @" using System; class Test { void M(Span<Test> $$) { } } " + Span; await VerifyItemExistsAsync(markup, "tests"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeValidGetEnumerator() { var markup = @" class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } public class MyEnumerator { public T Current { get; } public bool MoveNext() { return false; } } } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeValidGetAsyncEnumerator() { var markup = @" using System.Threading.Tasks; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> { public MyEnumerator GetAsyncEnumerator() { return new MyEnumerator(); } public class MyEnumerator { public T Current { get; } public Task<bool> MoveNextAsync() { return Task.FromResult(false); } } } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeForUnimplementedIEnumerable() { var markup = @" using System.Collections.Generic; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> : IEnumerable<T> { } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeForUnimplementedIAsyncEnumerable() { var markup = @" using System.Collections.Generic; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> : IAsyncEnumerable<T> { } " + IAsyncEnumerable; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching1() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; if (obj is CancellationToken $$) { } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching2() { var markup = @" using System.Threading; public class C { public static bool Foo() { object obj = null; return obj is CancellationToken $$ } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching3() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; switch(obj) { case CancellationToken $$ } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching4() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; if (obj is CancellationToken ca$$) { } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching5() { var markup = @" using System.Threading; public class C { public static bool Foo() { object obj = null; return obj is CancellationToken to$$ } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching6() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; switch(obj) { case CancellationToken to$$ } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "token"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement1() { var markup = @" using System.IO; class C { void M() { using (StreamReader s$$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement2() { var markup = @" using System.IO; class C { void M() { using (StreamReader s1, $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement_Var() { var markup = @" using System.IO; class C { void M() { using (var m$$ = new MemoryStream()) } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement1() { var markup = @" using System.IO; class C { void M() { for (StreamReader s$$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement2() { var markup = @" using System.IO; class C { void M() { for (StreamReader s1, $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement_Var() { var markup = @" using System.IO; class C { void M() { for (var m$$ = new MemoryStream(); } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [WorkItem(26021, "https://github.com/dotnet/roslyn/issues/26021")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForEachStatement() { var markup = @" using System.IO; class C { void M() { foreach (StreamReader $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForEachStatement_Var() { var markup = @" using System.IO; class C { void M() { foreach (var m$$ in new[] { new MemoryStream() }) } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DisabledByOption() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, false))); var markup = @" class Test { Test $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class Container : ContainerBase { } public class ContainerBase : IEnumerable<ContainerBase> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType2() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class ContainerBase : IEnumerable<Container> { } public class Container : ContainerBase { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType3() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class Container : IEnumerable<Container> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType4() { var markup = @" using System.Collections.Generic; using System.Threading.Tasks; public class Class1 { public void Method() { TaskType $$ } } public class ContainerBase : IEnumerable<Container> { } public class Container : ContainerBase { } public class TaskType : Task<Container> { } "; await VerifyItemExistsAsync(markup, "taskType"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType() { var markup = @" using System.Threading.Tasks; public class Class1 { public void Method() { Container $$ } } public class Container : ContainerBase { } public class ContainerBase : Task<ContainerBase> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType2() { var markup = @" using System.Threading.Tasks; public class Class1 { public void Method() { Container $$ } } public class Container : Task<ContainerBase> { } public class ContainerBase : Container { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType3() { var markup = @" using System.Collections.Generic; using System.Threading.Tasks; public class Class1 { public void Method() { EnumerableType $$ } } public class TaskType : TaskTypeBase { } public class TaskTypeBase : Task<TaskTypeBase> { } public class EnumerableType : IEnumerable<TaskType> { } "; await VerifyItemExistsAsync(markup, "taskTypes"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableOfNullable() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { // This code isn't legal, but we want to ensure we don't crash in this broken code scenario IEnumerable<Nullable<int?>> $$ } } "; await VerifyItemExistsAsync(markup, "nullables"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInLocalWithNullableTypeName() { var markup = @" using System; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method() { Nullable<ImmutableArray<int>> $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInLocalWithQuestionMark() { var markup = @" using System.Collections.Immutable; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method() { ImmutableArray<int>? $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableReferenceInLocal() { var markup = @" #nullable enable using System.Collections.Generic; public class Class1 { public void Method() { IEnumerable<int>? $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInParameterWithNullableTypeName() { var markup = @" using System; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method(Nullable<ImmutableArray<int>> $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInParameterWithQuestionMark() { var markup = @" public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method(ImmutableArray<int>? $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableReferenceInParameter() { var markup = @" #nullable enable using System.Collections.Generic; public class Class1 { public void Method(IEnumerable<int>? $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CustomNamingStyleInsideClass() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" class Configuration { Configuration $$ } "; await VerifyItemExistsAsync(markup, "ConfigurationField", glyph: (int)Glyph.FieldPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationProperty", glyph: (int)Glyph.PropertyPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationMethod", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "ConfigurationLocal"); await VerifyItemIsAbsentAsync(markup, "ConfigurationLocalFunction"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CustomNamingStyleInsideMethod() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" class Configuration { void M() { Configuration $$ } } "; await VerifyItemExistsAsync(markup, "ConfigurationLocal", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationLocalFunction", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "ConfigurationField"); await VerifyItemIsAbsentAsync(markup, "ConfigurationMethod"); await VerifyItemIsAbsentAsync(markup, "ConfigurationProperty"); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseForeachVariableName() { var markup = @" class ClassA { class ClassB {} readonly List<ClassB> classBList; void M() { foreach (var classB in classBList) { ClassB $$ } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseParameterName() { var markup = @" class ClassA { class ClassB { } void M(ClassB classB) { ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUsePropertyName() { var markup = @" class ClassA { class ClassB { } ClassB classB { get; set; } void M() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseFieldName() { var markup = @" class ClassA { class ClassB { } ClassB classB; void M() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalName() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalNameMultiple() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); ClassB classB1 = new ClassB(); ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemIsAbsentAsync(markup, "classB1"); await VerifyItemExistsAsync(markup, "classB2", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalInsideIf() { var markup = @" class ClassA { class ClassB { } void M(bool flag) { ClassB $$ if (flag) { ClassB classB = new ClassB(); } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseClassName() { var markup = @" class classA { void M() { classA $$ } } "; await VerifyItemExistsAsync(markup, "classA", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalInDifferentScope() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); } void M2() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] public async Task TestUseLocalAsLocalFunctionParameter(LanguageVersion languageVersion) { var source = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1(ClassB $$) { } } } "; var markup = GetMarkup(source, languageVersion); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } else { await VerifyItemIsAbsentAsync(markup, "classB"); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] public async Task TestCompletionDoesNotUseLocalAsLocalFunctionVariable(LanguageVersion languageVersion) { var source = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1() { ClassB $$ } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalInNestedLocalFunction() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1() { void LocalM2() { ClassB $$ } } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalFunctionParameterInNestedLocalFunction() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { void LocalM2() { ClassB $$ } } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionParameterAsParameter() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { } void LocalM2(ClassB $$) { } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionVariableAsParameter() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1() { ClassB classB } void LocalM2(ClassB $$) { } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionParameterAsVariable() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { } void LocalM2() { ClassB $$ } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionVariableAsVariable() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1() { ClassB classB } void LocalM2() { ClassB $$ } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(43816, "https://github.com/dotnet/roslyn/pull/43816")] public async Task ConflictingLocalVariable() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), MultipleCamelCaseLocalRules()))); var markup = @" public class MyClass { void M() { MyClass myClass; MyClass $$ } } "; await VerifyItemExistsAsync(markup, "myClass1", glyph: (int)Glyph.Local); } private static NamingStylePreferences MultipleCamelCaseLocalRules() { var styles = new[] { SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), name: "Local1"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), name: "Local1"), }; return new NamingStylePreferences( styles.Select(t => t.specification).ToImmutableArray(), styles.Select(t => t.style).ToImmutableArray(), styles.Select(t => CreateRule(t.specification, t.style)).ToImmutableArray()); // Local functions static (SymbolSpecification specification, NamingStyle style) SpecificationStyle(SymbolKindOrTypeKind kind, string name) { var symbolSpecification = new SymbolSpecification( id: null, symbolSpecName: name, ImmutableArray.Create(kind)); var namingStyle = new NamingStyle( Guid.NewGuid(), name, capitalizationScheme: Capitalization.CamelCase); return (symbolSpecification, namingStyle); } } private static NamingStylePreferences NamesEndWithSuffixPreferences() { var specificationStyles = new[] { SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Field), "Field"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Property), "Property"), SpecificationStyle(new SymbolKindOrTypeKind(MethodKind.Ordinary), "Method"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), "Local"), SpecificationStyle(new SymbolKindOrTypeKind(MethodKind.LocalFunction), "LocalFunction"), }; return new NamingStylePreferences( specificationStyles.Select(t => t.specification).ToImmutableArray(), specificationStyles.Select(t => t.style).ToImmutableArray(), specificationStyles.Select(t => CreateRule(t.specification, t.style)).ToImmutableArray()); // Local functions static (SymbolSpecification specification, NamingStyle style) SpecificationStyle(SymbolKindOrTypeKind kind, string suffix) { var symbolSpecification = new SymbolSpecification( id: null, symbolSpecName: suffix, ImmutableArray.Create(kind), accessibilityList: default, modifiers: default); var namingStyle = new NamingStyle( Guid.NewGuid(), name: suffix, capitalizationScheme: Capitalization.PascalCase, prefix: "", suffix: suffix, wordSeparator: ""); return (symbolSpecification, namingStyle); } } private static SerializableNamingRule CreateRule(SymbolSpecification specification, NamingStyle style) { return new SerializableNamingRule() { SymbolSpecificationID = specification.ID, NamingStyleID = style.ID, EnforcementLevel = ReportDiagnostic.Error }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { public class DeclarationNameCompletionProviderTests : AbstractCSharpCompletionProviderTests { private const string Span = @" namespace System { public readonly ref struct Span<T> { private readonly T[] arr; public ref T this[int i] => ref arr[i]; public override int GetHashCode() => 1; public int Length { get; } unsafe public Span(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public Span(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { get => ref _span[_index]; } } public static implicit operator Span<T>(T[] array) => new Span<T>(array); public Span<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new Span<T>(copy); } } public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public ref readonly T this[int i] => ref arr[i]; public override int GetHashCode() => 2; public int Length { get; } unsafe public ReadOnlySpan(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly ReadOnlySpan<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref readonly T Current { get => ref _span[_index]; } } public static implicit operator ReadOnlySpan<T>(T[] array) => array == null ? default : new ReadOnlySpan<T>(array); public static implicit operator ReadOnlySpan<T>(string stringValue) => string.IsNullOrEmpty(stringValue) ? default : new ReadOnlySpan<T>((T[])(object)stringValue.ToCharArray()); public ReadOnlySpan<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new ReadOnlySpan<T>(copy); } } public readonly ref struct SpanLike<T> { public readonly Span<T> field; } public enum Color: sbyte { Red, Green, Blue } public static unsafe class Helpers { public static T[] ToArray<T>(void* ptr, int count) { if (ptr == null) { return null; } if (typeof(T) == typeof(int)) { var arr = new int[count]; for(int i = 0; i < count; i++) { arr[i] = ((int*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(byte)) { var arr = new byte[count]; for(int i = 0; i < count; i++) { arr[i] = ((byte*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(char)) { var arr = new char[count]; for(int i = 0; i < count; i++) { arr[i] = ((char*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(Color)) { var arr = new Color[count]; for(int i = 0; i < count; i++) { arr[i] = ((Color*)ptr)[i]; } return (T[])(object)arr; } throw new Exception(""add a case for: "" + typeof(T)); } } }"; private const string IAsyncEnumerable = @" namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Runtime.CompilerServices { using System.Threading.Tasks; public sealed class AsyncMethodBuilderAttribute : Attribute { public AsyncMethodBuilderAttribute(Type builderType) { } public Type BuilderType { get; } } public struct AsyncValueTaskMethodBuilder { public ValueTask Task => default; public static AsyncValueTaskMethodBuilder Create() => default; public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {} public void SetException(Exception exception) {} public void SetResult() {} public void SetStateMachine(IAsyncStateMachine stateMachine) {} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {} } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public void GetResult() { } public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public TResult GetResult() => default; public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } } namespace System.Threading.Tasks { using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable<ValueTask> { public ValueTask(Task task) {} public ValueTask(IValueTaskSource source, short token) {} public bool IsCompleted => default; public bool IsCompletedSuccessfully => default; public bool IsFaulted => default; public bool IsCanceled => default; public Task AsTask() => default; public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => default; public override bool Equals(object obj) => default; public bool Equals(ValueTask other) => default; public ValueTaskAwaiter GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask Preserve() => default; public static bool operator ==(ValueTask left, ValueTask right) => default; public static bool operator !=(ValueTask left, ValueTask right) => default; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { public ValueTask(TResult result) {} public ValueTask(Task<TResult> task) {} public ValueTask(IValueTaskSource<TResult> source, short token) {} public bool IsFaulted => default; public bool IsCompletedSuccessfully => default; public bool IsCompleted => default; public bool IsCanceled => default; public TResult Result => default; public Task<TResult> AsTask() => default; public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) => default; public bool Equals(ValueTask<TResult> other) => default; public override bool Equals(object obj) => default; public ValueTaskAwaiter<TResult> GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask<TResult> Preserve() => default; public override string ToString() => default; public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) => default; public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) => default; } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } }"; internal override Type GetCompletionProviderType() => typeof(DeclarationNameCompletionProvider); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48310, "https://github.com/dotnet/roslyn/issues/48310")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TreatRecordPositionalParameterAsProperty(string record) { var markup = $@" public class MyClass {{ }} public {record} R(MyClass $$ "; await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameWithOnlyType1() { var markup = @" public class MyClass { MyClass $$ } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.FieldPublic); await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic); await VerifyItemExistsAsync(markup, "GetMyClass", glyph: (int)Glyph.MethodPublic); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncTaskOfT() { var markup = @" using System.Threading.Tasks; public class C { async Task<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCAsync"); } [Fact(Skip = "not yet implemented"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task NonAsyncTaskOfT() { var markup = @" public class C { Task<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration1() { var markup = @" public class C { virtual C $$ } "; await VerifyItemExistsAsync(markup, "GetC"); await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "c"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking1() { var markup = @" using System.Threading; public class C { CancellationToken $$ } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking2() { var markup = @" interface I {} public class C { I $$ } "; await VerifyItemExistsAsync(markup, "GetI"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking3() { var markup = @" interface II {} public class C { II $$ } "; await VerifyItemExistsAsync(markup, "GetI"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking4() { var markup = @" interface IGoo {} public class C { IGoo $$ } "; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WordBreaking5() { var markup = @" class SomeWonderfullyLongClassName {} public class C { SomeWonderfullyLongClassName $$ } "; await VerifyItemExistsAsync(markup, "Some"); await VerifyItemExistsAsync(markup, "SomeWonderfully"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLong"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLongClass"); await VerifyItemExistsAsync(markup, "Name"); await VerifyItemExistsAsync(markup, "ClassName"); await VerifyItemExistsAsync(markup, "LongClassName"); await VerifyItemExistsAsync(markup, "WonderfullyLongClassName"); await VerifyItemExistsAsync(markup, "SomeWonderfullyLongClassName"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter1() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken $$ } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter2() { var markup = @" using System.Threading; public class C { void Goo(int x, CancellationToken c$$ } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter3() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter4() { var markup = @" using System.Threading; public class C { void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter5() { var markup = @" using System.Threading; public class C { void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} } "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter6() { var markup = @" using System.Threading; void Other(CancellationToken cancellationToken) {} void Goo(CancellationToken c$$) {} "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter7() { var markup = @" using System.Threading; void Goo(CancellationToken cancellationToken, CancellationToken c$$) {} "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter8() { var markup = @" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken c$$] => throw null; } "; await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter9() { var markup = @" using System.Threading; public class C { int this[CancellationToken cancellationToken] => throw null; int this[CancellationToken cancellationToken, CancellationToken c$$] => throw null; } "; await VerifyItemExistsAsync(markup, "cancellationToken1", glyph: (int)Glyph.Parameter); } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter10(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { void Goo(DbContext context) { void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter11(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { void Goo() { DbContext context; void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] [WorkItem(45492, "https://github.com/dotnet/roslyn/issues/45492")] public async Task Parameter12(LanguageVersion languageVersion) { var source = @" public class DbContext { } public class C { DbContext dbContext; void Goo(DbContext context) { void InnerGoo(DbContext $$) { } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemExistsAsync(markup, "dbContext", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "db", glyph: (int)Glyph.Parameter); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "context", glyph: (int)Glyph.Parameter); } else { await VerifyItemExistsAsync(markup, "context1", glyph: (int)Glyph.Parameter); } } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords1() { var markup = @" using System.Text; public class C { void Goo(StringBuilder $$) {} } "; await VerifyItemExistsAsync(markup, "stringBuilder", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "@string", glyph: (int)Glyph.Parameter); await VerifyItemExistsAsync(markup, "builder", glyph: (int)Glyph.Parameter); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords2() { var markup = @" class For { } public class C { void Goo(For $$) {} } "; await VerifyItemExistsAsync(markup, "@for", glyph: (int)Glyph.Parameter); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords3() { var markup = @" class For { } public class C { void goo() { For $$ } } "; await VerifyItemExistsAsync(markup, "@for"); } [WorkItem(19260, "https://github.com/dotnet/roslyn/issues/19260")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapeKeywords4() { var markup = @" using System.Text; public class C { void goo() { StringBuilder $$ } } "; await VerifyItemExistsAsync(markup, "stringBuilder"); await VerifyItemExistsAsync(markup, "@string"); await VerifyItemExistsAsync(markup, "builder"); } [WorkItem(25214, "https://github.com/dotnet/roslyn/issues/25214")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsLazyOfType1() { var markup = @" using System; using System.Collections.Generic; internal class Example { public Lazy<Item> $$ } public class Item { } "; await VerifyItemExistsAsync(markup, "item"); await VerifyItemExistsAsync(markup, "Item"); await VerifyItemExistsAsync(markup, "GetItem"); } [WorkItem(25214, "https://github.com/dotnet/roslyn/issues/25214")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsLazyOfType2() { var markup = @" using System; using System.Collections.Generic; internal class Example { public List<Lazy<Item>> $$ } public class Item { } "; await VerifyItemExistsAsync(markup, "items"); await VerifyItemExistsAsync(markup, "Items"); await VerifyItemExistsAsync(markup, "GetItems"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForInt() { var markup = @" using System.Threading; public class C { int $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForLong() { var markup = @" using System.Threading; public class C { long $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForDouble() { var markup = @" using System.Threading; public class C { double $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForFloat() { var markup = @" using System.Threading; public class C { float $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForSbyte() { var markup = @" using System.Threading; public class C { sbyte $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForShort() { var markup = @" using System.Threading; public class C { short $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForUint() { var markup = @" using System.Threading; public class C { uint $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForUlong() { var markup = @" using System.Threading; public class C { ulong $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestionsForUShort() { var markup = @" using System.Threading; public class C { ushort $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForBool() { var markup = @" using System.Threading; public class C { bool $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForByte() { var markup = @" using System.Threading; public class C { byte $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForChar() { var markup = @" using System.Threading; public class C { char $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSuggestionsForString() { var markup = @" public class C { string $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoSingleLetterClassNameSuggested() { var markup = @" public class C { C $$ } "; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "c"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayElementTypeSuggested() { var markup = @" using System.Threading; public class MyClass { MyClass[] $$ } "; await VerifyItemExistsAsync(markup, "MyClasses"); await VerifyItemIsAbsentAsync(markup, "Array"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotTriggeredByVar() { var markup = @" public class C { var $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoid() { var markup = @" public class C { void $$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterGeneric() { var markup = @" public class C { System.Collections.Generic.IEnumerable<C> $$ } "; await VerifyItemExistsAsync(markup, "GetCs"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterVar() { var markup = @" public class C { void goo() { var $$ } } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCorrectOrder() { var markup = @" public class MyClass { MyClass $$ } "; var items = await GetCompletionItemsAsync(markup, SourceCodeKind.Regular); Assert.Equal( new[] { "myClass", "my", "@class", "MyClass", "My", "Class", "GetMyClass", "GetMy", "GetClass" }, items.Select(item => item.DisplayText)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDescriptionInsideClass() { var markup = @" public class MyClass { MyClass $$ } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.FieldPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.PropertyPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "GetMyClass", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDescriptionInsideMethod() { var markup = @" public class MyClass { void M() { MyClass $$ } } "; await VerifyItemExistsAsync(markup, "myClass", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "MyClass"); await VerifyItemIsAbsentAsync(markup, "GetMyClass"); } [WorkItem(20273, "https://github.com/dotnet/roslyn/issues/20273")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Alias1() { var markup = @" using MyType = System.String; public class C { MyType $$ } "; await VerifyItemExistsAsync(markup, "my"); await VerifyItemExistsAsync(markup, "type"); await VerifyItemExistsAsync(markup, "myType"); } [WorkItem(20273, "https://github.com/dotnet/roslyn/issues/20273")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasWithInterfacePattern() { var markup = @" using IMyType = System.String; public class C { MyType $$ } "; await VerifyItemExistsAsync(markup, "my"); await VerifyItemExistsAsync(markup, "type"); await VerifyItemExistsAsync(markup, "myType"); } [WorkItem(20016, "https://github.com/dotnet/roslyn/issues/20016")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExistingName1() { var markup = @" using IMyType = System.String; public class C { MyType myType $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(20016, "https://github.com/dotnet/roslyn/issues/20016")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExistingName2() { var markup = @" using IMyType = System.String; public class C { MyType myType, MyType $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutVarArgument() { var markup = @" class Test { void Do(out Test goo) { Do(out var $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutArgument() { var markup = @" class Test { void Do(out Test goo) { Do(out Test $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(19409, "https://github.com/dotnet/roslyn/issues/19409")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutGenericArgument() { var markup = @" class Test { void Do<T>(out T goo) { Do(out Test $$ } } "; await VerifyItemExistsAsync(markup, "test"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration1() { var markup = @" class Test { void Do() { (System.Array array, System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration2() { var markup = @" class Test { void Do() { (array, action $$ } } "; await VerifyItemIsAbsentAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration_NestedTuples() { var markup = @" class Test { void Do() { ((int i1, int i2), (System.Array array, System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionDeclaration_NestedTuples_CompletionInTheMiddle() { var markup = @" class Test { void Do() { ((System.Array array, System.Action $$), (int i1, int i2)) } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition1() { var markup = @" class Test { void Do() { (System.Array $$ } } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition2() { var markup = @" class Test { (System.Array $$) Test() => default; } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition3() { var markup = @" class Test { (System.Array array, System.Action $$) Test() => default; } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition4() { var markup = @" class Test { (System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition5() { var markup = @" class Test { void M((System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition_NestedTuples() { var markup = @" class Test { void M(((int, int), (int, System.Array $$ } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementDefinition_InMiddleOfTuple() { var markup = @" class Test { void M((int, System.Array $$),int) } "; await VerifyItemExistsAsync(markup, "array"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementTypeInference() { var markup = @" class Test { void Do() { (var accessViolationException, var $$) = (new AccessViolationException(), new Action(() => { })); } } "; // Currently not supported: await VerifyItemIsAbsentAsync(markup, "action"); // see https://github.com/dotnet/roslyn/issues/27138 // after the issue ist fixed we expect this to work: // await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact(Skip = "Not yet supported"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementInGenericTypeArgument() { var markup = @" class Test { void Do() { System.Func<(System.Action $$ } } "; await VerifyItemExistsAsync(markup, "action"); } [WorkItem(22342, "https://github.com/dotnet/roslyn/issues/22342")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementInvocationInsideTuple() { var markup = @" class Test { void Do() { int M(int i1, int i2) => i1; var t=(e1: 1, e2: M(1, $$)); } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize1() { var markup = @" using System.Collections.Generic; class Index { IEnumerable<Index> $$ } "; await VerifyItemExistsAsync(markup, "Indices"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize2() { var markup = @" using System.Collections.Generic; class Test { IEnumerable<IEnumerable<Test>> $$ } "; await VerifyItemExistsAsync(markup, "tests"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Pluralize3() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { IEnumerable<CancellationToken> $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeList() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { List<CancellationToken> $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(17987, "https://github.com/dotnet/roslyn/issues/17987")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeArray() { var markup = @" using System.Collections.Generic; using System.Threading; class Test { CancellationToken[] $$ } "; await VerifyItemExistsAsync(markup, "cancellationTokens"); await VerifyItemExistsAsync(markup, "cancellations"); await VerifyItemExistsAsync(markup, "tokens"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeSpan() { var markup = @" using System; class Test { void M(Span<Test> $$) { } } " + Span; await VerifyItemExistsAsync(markup, "tests"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeValidGetEnumerator() { var markup = @" class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } public class MyEnumerator { public T Current { get; } public bool MoveNext() { return false; } } } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeValidGetAsyncEnumerator() { var markup = @" using System.Threading.Tasks; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> { public MyEnumerator GetAsyncEnumerator() { return new MyEnumerator(); } public class MyEnumerator { public T Current { get; } public Task<bool> MoveNextAsync() { return Task.FromResult(false); } } } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeForUnimplementedIEnumerable() { var markup = @" using System.Collections.Generic; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> : IEnumerable<T> { } "; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(37366, "https://github.com/dotnet/roslyn/issues/37366")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PluralizeForUnimplementedIAsyncEnumerable() { var markup = @" using System.Collections.Generic; class MyClass { public void M(MyOwnCollection<MyClass> $$) { } } class MyOwnCollection<T> : IAsyncEnumerable<T> { } " + IAsyncEnumerable; await VerifyItemExistsAsync(markup, "myClasses"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching1() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; if (obj is CancellationToken $$) { } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching2() { var markup = @" using System.Threading; public class C { public static bool Foo() { object obj = null; return obj is CancellationToken $$ } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching3() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; switch(obj) { case CancellationToken $$ } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching4() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; if (obj is CancellationToken ca$$) { } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "cancellation"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching5() { var markup = @" using System.Threading; public class C { public static bool Foo() { object obj = null; return obj is CancellationToken to$$ } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "token"); } [WorkItem(23497, "https://github.com/dotnet/roslyn/issues/23497")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InPatternMatching6() { var markup = @" using System.Threading; public class C { public static void Main() { object obj = null; switch(obj) { case CancellationToken to$$ } } } "; await VerifyItemExistsAsync(markup, "cancellationToken"); await VerifyItemExistsAsync(markup, "token"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement1() { var markup = @" using System.IO; class C { void M() { using (StreamReader s$$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement2() { var markup = @" using System.IO; class C { void M() { using (StreamReader s1, $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InUsingStatement_Var() { var markup = @" using System.IO; class C { void M() { using (var m$$ = new MemoryStream()) } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement1() { var markup = @" using System.IO; class C { void M() { for (StreamReader s$$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement2() { var markup = @" using System.IO; class C { void M() { for (StreamReader s1, $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForStatement_Var() { var markup = @" using System.IO; class C { void M() { for (var m$$ = new MemoryStream(); } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [WorkItem(26021, "https://github.com/dotnet/roslyn/issues/26021")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForEachStatement() { var markup = @" using System.IO; class C { void M() { foreach (StreamReader $$ } } "; await VerifyItemExistsAsync(markup, "streamReader"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InForEachStatement_Var() { var markup = @" using System.IO; class C { void M() { foreach (var m$$ in new[] { new MemoryStream() }) } } "; await VerifyItemExistsAsync(markup, "memoryStream"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DisabledByOption() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, false))); var markup = @" class Test { Test $$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class Container : ContainerBase { } public class ContainerBase : IEnumerable<ContainerBase> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType2() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class ContainerBase : IEnumerable<Container> { } public class Container : ContainerBase { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType3() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { Container $$ } } public class Container : IEnumerable<Container> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsIEnumerableOfType4() { var markup = @" using System.Collections.Generic; using System.Threading.Tasks; public class Class1 { public void Method() { TaskType $$ } } public class ContainerBase : IEnumerable<Container> { } public class Container : ContainerBase { } public class TaskType : Task<Container> { } "; await VerifyItemExistsAsync(markup, "taskType"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType() { var markup = @" using System.Threading.Tasks; public class Class1 { public void Method() { Container $$ } } public class Container : ContainerBase { } public class ContainerBase : Task<ContainerBase> { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType2() { var markup = @" using System.Threading.Tasks; public class Class1 { public void Method() { Container $$ } } public class Container : Task<ContainerBase> { } public class ContainerBase : Container { } "; await VerifyItemExistsAsync(markup, "container"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeImplementsTaskOfType3() { var markup = @" using System.Collections.Generic; using System.Threading.Tasks; public class Class1 { public void Method() { EnumerableType $$ } } public class TaskType : TaskTypeBase { } public class TaskTypeBase : Task<TaskTypeBase> { } public class EnumerableType : IEnumerable<TaskType> { } "; await VerifyItemExistsAsync(markup, "taskTypes"); } [WorkItem(23590, "https://github.com/dotnet/roslyn/issues/23590")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableOfNullable() { var markup = @" using System.Collections.Generic; public class Class1 { public void Method() { // This code isn't legal, but we want to ensure we don't crash in this broken code scenario IEnumerable<Nullable<int?>> $$ } } "; await VerifyItemExistsAsync(markup, "nullables"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInLocalWithNullableTypeName() { var markup = @" using System; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method() { Nullable<ImmutableArray<int>> $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInLocalWithQuestionMark() { var markup = @" using System.Collections.Immutable; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method() { ImmutableArray<int>? $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableReferenceInLocal() { var markup = @" #nullable enable using System.Collections.Generic; public class Class1 { public void Method() { IEnumerable<int>? $$ } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInParameterWithNullableTypeName() { var markup = @" using System; public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method(Nullable<ImmutableArray<int>> $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableStructInParameterWithQuestionMark() { var markup = @" public struct ImmutableArray<T> : System.Collections.Generic.IEnumerable<T> { } public class Class1 { public void Method(ImmutableArray<int>? $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [WorkItem(1220195, "https://developercommunity2.visualstudio.com/t/Regression-from-1675-Suggested-varia/1220195")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeIsNullableReferenceInParameter() { var markup = @" #nullable enable using System.Collections.Generic; public class Class1 { public void Method(IEnumerable<int>? $$) { } } "; await VerifyItemExistsAsync(markup, "vs"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CustomNamingStyleInsideClass() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" class Configuration { Configuration $$ } "; await VerifyItemExistsAsync(markup, "ConfigurationField", glyph: (int)Glyph.FieldPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationProperty", glyph: (int)Glyph.PropertyPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationMethod", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "ConfigurationLocal"); await VerifyItemIsAbsentAsync(markup, "ConfigurationLocalFunction"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CustomNamingStyleInsideMethod() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" class Configuration { void M() { Configuration $$ } } "; await VerifyItemExistsAsync(markup, "ConfigurationLocal", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemExistsAsync(markup, "ConfigurationLocalFunction", glyph: (int)Glyph.MethodPublic, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); await VerifyItemIsAbsentAsync(markup, "ConfigurationField"); await VerifyItemIsAbsentAsync(markup, "ConfigurationMethod"); await VerifyItemIsAbsentAsync(markup, "ConfigurationProperty"); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseForeachVariableName() { var markup = @" class ClassA { class ClassB {} readonly List<ClassB> classBList; void M() { foreach (var classB in classBList) { ClassB $$ } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseParameterName() { var markup = @" class ClassA { class ClassB { } void M(ClassB classB) { ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUsePropertyName() { var markup = @" class ClassA { class ClassB { } ClassB classB { get; set; } void M() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseFieldName() { var markup = @" class ClassA { class ClassB { } ClassB classB; void M() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalName() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalNameMultiple() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); ClassB classB1 = new ClassB(); ClassB $$ } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemIsAbsentAsync(markup, "classB1"); await VerifyItemExistsAsync(markup, "classB2", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalInsideIf() { var markup = @" class ClassA { class ClassB { } void M(bool flag) { ClassB $$ if (flag) { ClassB classB = new ClassB(); } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); await VerifyItemExistsAsync(markup, "classB1", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseClassName() { var markup = @" class classA { void M() { classA $$ } } "; await VerifyItemExistsAsync(markup, "classA", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalInDifferentScope() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); } void M2() { ClassB $$ } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] public async Task TestUseLocalAsLocalFunctionParameter(LanguageVersion languageVersion) { var source = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1(ClassB $$) { } } } "; var markup = GetMarkup(source, languageVersion); if (languageVersion.MapSpecifiedToEffectiveVersion() >= LanguageVersion.CSharp8) { await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } else { await VerifyItemIsAbsentAsync(markup, "classB"); } } [InlineData(LanguageVersion.CSharp7)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.Latest)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [WorkItem(42049, "https://github.com/dotnet/roslyn/issues/42049")] public async Task TestCompletionDoesNotUseLocalAsLocalFunctionVariable(LanguageVersion languageVersion) { var source = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1() { ClassB $$ } } } "; var markup = GetMarkup(source, languageVersion); await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalInNestedLocalFunction() { var markup = @" class ClassA { class ClassB { } void M() { ClassB classB = new ClassB(); void LocalM1() { void LocalM2() { ClassB $$ } } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionDoesNotUseLocalFunctionParameterInNestedLocalFunction() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { void LocalM2() { ClassB $$ } } } } "; await VerifyItemIsAbsentAsync(markup, "classB"); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionParameterAsParameter() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { } void LocalM2(ClassB $$) { } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionVariableAsParameter() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1() { ClassB classB } void LocalM2(ClassB $$) { } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Parameter, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionParameterAsVariable() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1(ClassB classB) { } void LocalM2() { ClassB $$ } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [WorkItem(35891, "https://github.com/dotnet/roslyn/issues/35891")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCompletionCanUseLocalFunctionVariableAsVariable() { var markup = @" class ClassA { class ClassB { } void M() { void LocalM1() { ClassB classB } void LocalM2() { ClassB $$ } } } "; await VerifyItemExistsAsync(markup, "classB", glyph: (int)Glyph.Local, expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(43816, "https://github.com/dotnet/roslyn/pull/43816")] public async Task ConflictingLocalVariable() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), MultipleCamelCaseLocalRules()))); var markup = @" public class MyClass { void M() { MyClass myClass; MyClass $$ } } "; await VerifyItemExistsAsync(markup, "myClass1", glyph: (int)Glyph.Local); } private static NamingStylePreferences MultipleCamelCaseLocalRules() { var styles = new[] { SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), name: "Local1"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), name: "Local1"), }; return new NamingStylePreferences( styles.Select(t => t.specification).ToImmutableArray(), styles.Select(t => t.style).ToImmutableArray(), styles.Select(t => CreateRule(t.specification, t.style)).ToImmutableArray()); // Local functions static (SymbolSpecification specification, NamingStyle style) SpecificationStyle(SymbolKindOrTypeKind kind, string name) { var symbolSpecification = new SymbolSpecification( id: null, symbolSpecName: name, ImmutableArray.Create(kind)); var namingStyle = new NamingStyle( Guid.NewGuid(), name, capitalizationScheme: Capitalization.CamelCase); return (symbolSpecification, namingStyle); } } private static NamingStylePreferences NamesEndWithSuffixPreferences() { var specificationStyles = new[] { SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Field), "Field"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Property), "Property"), SpecificationStyle(new SymbolKindOrTypeKind(MethodKind.Ordinary), "Method"), SpecificationStyle(new SymbolKindOrTypeKind(SymbolKind.Local), "Local"), SpecificationStyle(new SymbolKindOrTypeKind(MethodKind.LocalFunction), "LocalFunction"), }; return new NamingStylePreferences( specificationStyles.Select(t => t.specification).ToImmutableArray(), specificationStyles.Select(t => t.style).ToImmutableArray(), specificationStyles.Select(t => CreateRule(t.specification, t.style)).ToImmutableArray()); // Local functions static (SymbolSpecification specification, NamingStyle style) SpecificationStyle(SymbolKindOrTypeKind kind, string suffix) { var symbolSpecification = new SymbolSpecification( id: null, symbolSpecName: suffix, ImmutableArray.Create(kind), accessibilityList: default, modifiers: default); var namingStyle = new NamingStyle( Guid.NewGuid(), name: suffix, capitalizationScheme: Capitalization.PascalCase, prefix: "", suffix: suffix, wordSeparator: ""); return (symbolSpecification, namingStyle); } } private static SerializableNamingRule CreateRule(SymbolSpecification specification, NamingStyle style) { return new SerializableNamingRule() { SymbolSpecificationID = specification.ID, NamingStyleID = style.ID, EnforcementLevel = ReportDiagnostic.Error }; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/Extensibility/Completion/ExportCompletionProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Completion; namespace Microsoft.CodeAnalysis.Editor { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportCompletionProviderMef1Attribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportCompletionProviderMef1Attribute(string name, string language) : base(typeof(CompletionProvider)) { this.Name = name ?? throw new ArgumentNullException(nameof(name)); this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Completion; namespace Microsoft.CodeAnalysis.Editor { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportCompletionProviderMef1Attribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportCompletionProviderMef1Attribute(string name, string language) : base(typeof(CompletionProvider)) { this.Name = name ?? throw new ArgumentNullException(nameof(name)); this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/IBindingRedirectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface IBindingRedirectionService { AssemblyIdentity ApplyBindingRedirects(AssemblyIdentity originalIdentity); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface IBindingRedirectionService { AssemblyIdentity ApplyBindingRedirects(AssemblyIdentity originalIdentity); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Test/Core/Compilation/NullErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; namespace Microsoft.CodeAnalysis.Test.Utilities { internal class NullErrorLogger : ErrorLogger { internal static ErrorLogger Instance => new NullErrorLogger(); public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; namespace Microsoft.CodeAnalysis.Test.Utilities { internal class NullErrorLogger : ErrorLogger { internal static ErrorLogger Instance => new NullErrorLogger(); public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerDisplayAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase { [Fact] public void WithoutExpressionHoles() { var source = @" using System.Diagnostics; class C0 { } [DebuggerDisplay(""Value"")] class C1 { } [DebuggerDisplay(""Value"", Name=""Name"")] class C2 { } [DebuggerDisplay(""Value"", Type=""Type"")] class C3 { } [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class C4 { } class Wrapper { C0 c0 = new C0(); C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None), EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None)); } [Fact] public void OnlyExpressionHoles() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("c", value)), EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void FormatStrings() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BindingError() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{missing}>"")] class C { } "; const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it. var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks. } [Fact] public void RecursiveDebuggerDisplay() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"")] class C { C value; C() { this.value = this; } } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // No stack overflow, since attribute on computed value is ignored. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); } [Fact] public void MultipleAttributes() { var source = @" using System.Diagnostics; [DebuggerDisplay(""V1"")] [DebuggerDisplay(""V2"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // First attribute wins, as in dev12. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "V1", "C", rootExpr)); } [Fact] public void NullValues() { var source = @" using System.Diagnostics; [DebuggerDisplay(null, Name=null, Type=null)] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr)); } [Fact] public void EmptyStringValues() { var source = @" using System.Diagnostics; [DebuggerDisplay("""", Name="""", Type="""")] class C { } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("", "", "", "w.c")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Name"")] class C<T> { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult("c", "Name", "C<int>", rootExpr)); } [Fact] public void MemberExpansion() { var source = @" using System.Diagnostics; interface I { D P { get; } } class C : I { D I.P { get { return new D(); } } D Q { get { return new D(); } } } [DebuggerDisplay(""Value"", Name=""Name"")] class D { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult(rootExpr, value); Verify(root, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(root), EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name". EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void PointerDereferenceExpansion_Null() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } class Wrapper { Display display = new Display(); } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("wrapper", value); Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3), EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"), EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer")); } [Fact] public void PointerDereferenceExpansion_NonNull() { var source = @" using System; using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe class C { Display* DisplayPointer; NoDisplay* NoDisplayPointer; public C(IntPtr d, IntPtr nd) { this.DisplayPointer = (Display*)d; this.NoDisplayPointer = (NoDisplay*)nd; this.DisplayPointer->DisplayPointer = this.DisplayPointer; this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer; this.NoDisplayPointer->DisplayPointer = this.DisplayPointer; this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer; } } "; var assembly = GetUnsafeAssembly(source); unsafe { var displayType = assembly.GetType("Display"); var displayInstance = displayType.Instantiate(); var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned); var displayPtr = displayHandle.AddrOfPinnedObject(); var noDisplayType = assembly.GetType("NoDisplay"); var noDisplayInstance = noDisplayType.Instantiate(); var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned); var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject(); var testType = assembly.GetType("C"); var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr); var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None); var displayPtrString = PointerToString(displayPtr); var noDisplayPtrString = PointerToString(noDisplayPtr); Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable)); displayHandle.Free(); noDisplayHandle.Free(); } } [Fact] public void ArrayExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] struct Display { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } struct NoDisplay { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } class C { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; public C() { this.DisplayArray = new[] { new Display() }; this.NoDisplayArray = new[] { new NoDisplay() }; this.DisplayArray[0].DisplayArray = this.DisplayArray; this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray; this.NoDisplayArray[0].DisplayArray = this.DisplayArray; this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray; } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void DebuggerTypeProxyExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] public struct Display { } public struct NoDisplay { } [DebuggerTypeProxy(typeof(P))] public class C { public Display DisplayC = new Display(); public NoDisplay NoDisplayC = new NoDisplay(); } public class P { public Display DisplayP = new Display(); public NoDisplay NoDisplayP = new NoDisplay(); public P(C c) { } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "new P(c).DisplayP"), EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"), EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Name", "Value", "Type", "c.DisplayC"), EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC")); } [Fact] public void NullInstance() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Hello"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "null", "C", rootExpr)); } [Fact] public void NonGenericDisplayAttributeOnGenericBase() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Type={GetType()}"")] class A<T> { } class B : A<int> { } "; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var result = FormatResult("b", value); Verify(result, EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None)); } [WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")] [Fact] public void RootVersusInternal() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name = ""Name"")] class A { } class B { A a; public B(A a) { this.a = a; } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var instanceA = typeA.Instantiate(); var instanceB = typeB.Instantiate(instanceA); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)); result = FormatResult("b", CreateDkmClrValue(instanceB)); Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None)); } [Fact] public void Error() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class A { } class B { bool f; internal A P { get { return new A(); } } internal A Q { get { while(f) { } return new A(); } } } "; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.CanFavorite)); } } [Fact] public void UnhandledException() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value}"")] class A { internal int Value; } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var instanceA = typeA.Instantiate(); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None)); } [Fact, WorkItem(171123, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv")] public void ExceptionDuringEvaluate() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Make it throw."")] public class Picard { } "; var assembly = GetAssembly(source); var picard = assembly.GetType("Picard"); var jeanLuc = picard.Instantiate(); var result = FormatAsyncResult("says", "says", CreateDkmClrValue(jeanLuc), declaredType: new BadType(picard)); Assert.Equal(BadType.Exception, result.Exception); } private class BadType : DkmClrType { public static readonly Exception Exception = new TargetInvocationException(new DkmException(DkmExceptionCode.E_PROCESS_DESTROYED)); public BadType(System.Type innerType) : base((TypeImpl)innerType) { } public override VisualStudio.Debugger.Metadata.Type GetLmrType() { if (Environment.StackTrace.Contains("Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.GetTypeName")) { throw Exception; } return base.GetLmrType(); } } private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth) { var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); DepthFirstSearchInternal(builder, root, 0, maxDepth); return builder.ToImmutableAndFree(); } private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth) { Assert.InRange(depth, 0, maxDepth); builder.Add(curr); var childDepth = depth + 1; if (childDepth <= maxDepth) { foreach (var child in GetChildren(curr)) { DepthFirstSearchInternal(builder, child, childDepth, maxDepth); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase { [Fact] public void WithoutExpressionHoles() { var source = @" using System.Diagnostics; class C0 { } [DebuggerDisplay(""Value"")] class C1 { } [DebuggerDisplay(""Value"", Name=""Name"")] class C2 { } [DebuggerDisplay(""Value"", Type=""Type"")] class C3 { } [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class C4 { } class Wrapper { C0 c0 = new C0(); C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None), EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None)); } [Fact] public void OnlyExpressionHoles() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("c", value)), EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void FormatStrings() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BindingError() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{missing}>"")] class C { } "; const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it. var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks. } [Fact] public void RecursiveDebuggerDisplay() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"")] class C { C value; C() { this.value = this; } } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // No stack overflow, since attribute on computed value is ignored. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); } [Fact] public void MultipleAttributes() { var source = @" using System.Diagnostics; [DebuggerDisplay(""V1"")] [DebuggerDisplay(""V2"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // First attribute wins, as in dev12. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "V1", "C", rootExpr)); } [Fact] public void NullValues() { var source = @" using System.Diagnostics; [DebuggerDisplay(null, Name=null, Type=null)] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr)); } [Fact] public void EmptyStringValues() { var source = @" using System.Diagnostics; [DebuggerDisplay("""", Name="""", Type="""")] class C { } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("", "", "", "w.c")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Name"")] class C<T> { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult("c", "Name", "C<int>", rootExpr)); } [Fact] public void MemberExpansion() { var source = @" using System.Diagnostics; interface I { D P { get; } } class C : I { D I.P { get { return new D(); } } D Q { get { return new D(); } } } [DebuggerDisplay(""Value"", Name=""Name"")] class D { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult(rootExpr, value); Verify(root, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(root), EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name". EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void PointerDereferenceExpansion_Null() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } class Wrapper { Display display = new Display(); } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("wrapper", value); Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3), EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"), EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer")); } [Fact] public void PointerDereferenceExpansion_NonNull() { var source = @" using System; using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe class C { Display* DisplayPointer; NoDisplay* NoDisplayPointer; public C(IntPtr d, IntPtr nd) { this.DisplayPointer = (Display*)d; this.NoDisplayPointer = (NoDisplay*)nd; this.DisplayPointer->DisplayPointer = this.DisplayPointer; this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer; this.NoDisplayPointer->DisplayPointer = this.DisplayPointer; this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer; } } "; var assembly = GetUnsafeAssembly(source); unsafe { var displayType = assembly.GetType("Display"); var displayInstance = displayType.Instantiate(); var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned); var displayPtr = displayHandle.AddrOfPinnedObject(); var noDisplayType = assembly.GetType("NoDisplay"); var noDisplayInstance = noDisplayType.Instantiate(); var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned); var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject(); var testType = assembly.GetType("C"); var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr); var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None); var displayPtrString = PointerToString(displayPtr); var noDisplayPtrString = PointerToString(noDisplayPtr); Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable)); displayHandle.Free(); noDisplayHandle.Free(); } } [Fact] public void ArrayExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] struct Display { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } struct NoDisplay { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } class C { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; public C() { this.DisplayArray = new[] { new Display() }; this.NoDisplayArray = new[] { new NoDisplay() }; this.DisplayArray[0].DisplayArray = this.DisplayArray; this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray; this.NoDisplayArray[0].DisplayArray = this.DisplayArray; this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray; } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void DebuggerTypeProxyExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] public struct Display { } public struct NoDisplay { } [DebuggerTypeProxy(typeof(P))] public class C { public Display DisplayC = new Display(); public NoDisplay NoDisplayC = new NoDisplay(); } public class P { public Display DisplayP = new Display(); public NoDisplay NoDisplayP = new NoDisplay(); public P(C c) { } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "new P(c).DisplayP"), EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"), EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Name", "Value", "Type", "c.DisplayC"), EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC")); } [Fact] public void NullInstance() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Hello"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "null", "C", rootExpr)); } [Fact] public void NonGenericDisplayAttributeOnGenericBase() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Type={GetType()}"")] class A<T> { } class B : A<int> { } "; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var result = FormatResult("b", value); Verify(result, EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None)); } [WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")] [Fact] public void RootVersusInternal() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name = ""Name"")] class A { } class B { A a; public B(A a) { this.a = a; } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var instanceA = typeA.Instantiate(); var instanceB = typeB.Instantiate(instanceA); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)); result = FormatResult("b", CreateDkmClrValue(instanceB)); Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None)); } [Fact] public void Error() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class A { } class B { bool f; internal A P { get { return new A(); } } internal A Q { get { while(f) { } return new A(); } } } "; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.CanFavorite)); } } [Fact] public void UnhandledException() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value}"")] class A { internal int Value; } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var instanceA = typeA.Instantiate(); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None)); } [Fact, WorkItem(171123, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv")] public void ExceptionDuringEvaluate() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Make it throw."")] public class Picard { } "; var assembly = GetAssembly(source); var picard = assembly.GetType("Picard"); var jeanLuc = picard.Instantiate(); var result = FormatAsyncResult("says", "says", CreateDkmClrValue(jeanLuc), declaredType: new BadType(picard)); Assert.Equal(BadType.Exception, result.Exception); } private class BadType : DkmClrType { public static readonly Exception Exception = new TargetInvocationException(new DkmException(DkmExceptionCode.E_PROCESS_DESTROYED)); public BadType(System.Type innerType) : base((TypeImpl)innerType) { } public override VisualStudio.Debugger.Metadata.Type GetLmrType() { if (Environment.StackTrace.Contains("Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.GetTypeName")) { throw Exception; } return base.GetLmrType(); } } private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth) { var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); DepthFirstSearchInternal(builder, root, 0, maxDepth); return builder.ToImmutableAndFree(); } private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth) { Assert.InRange(depth, 0, maxDepth); builder.Add(curr); var childDepth = depth + 1; if (childDepth <= maxDepth) { foreach (var child in GetChildren(curr)) { DepthFirstSearchInternal(builder, child, childDepth, maxDepth); } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/View/ColumnDefnitions/WhitespaceDescriptionColumnDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Description)] internal class WhitespaceDescriptionColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceDescriptionColumnDefinition() { } public override string Name => Description; public override string DisplayName => ServicesVSResources.Description; public override bool IsFilterable => false; public override bool IsSortable => false; public override double DefaultWidth => 350; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Description)] internal class WhitespaceDescriptionColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceDescriptionColumnDefinition() { } public override string Name => Description; public override string DisplayName => ServicesVSResources.Description; public override bool IsFilterable => false; public override bool IsSortable => false; public override double DefaultWidth => 350; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Test/Utilities/PatternMatcherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class PatternMatcherTests { [Fact] public void BreakIntoCharacterParts_EmptyIdentifier() => VerifyBreakIntoCharacterParts(string.Empty, Array.Empty<string>()); [Fact] public void BreakIntoCharacterParts_SimpleIdentifier() => VerifyBreakIntoCharacterParts("goo", "goo"); [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifier() => VerifyBreakIntoCharacterParts("_goo", "_", "goo"); [Fact] public void BreakIntoCharacterParts_UnderscoredIdentifier() => VerifyBreakIntoCharacterParts("g_oo", "g", "_", "oo"); [Fact] public void BreakIntoCharacterParts_PostfixUnderscoredIdentifier() => VerifyBreakIntoCharacterParts("goo_", "goo", "_"); [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifierWithCapital() => VerifyBreakIntoCharacterParts("_Goo", "_", "Goo"); [Fact] public void BreakIntoCharacterParts_MUnderscorePrefixed() => VerifyBreakIntoCharacterParts("m_goo", "m", "_", "goo"); [Fact] public void BreakIntoCharacterParts_CamelCaseIdentifier() => VerifyBreakIntoCharacterParts("FogBar", "Fog", "Bar"); [Fact] public void BreakIntoCharacterParts_MixedCaseIdentifier() => VerifyBreakIntoCharacterParts("fogBar", "fog", "Bar"); [Fact] public void BreakIntoCharacterParts_TwoCharacterCapitalIdentifier() => VerifyBreakIntoCharacterParts("UIElement", "U", "I", "Element"); [Fact] public void BreakIntoCharacterParts_NumberSuffixedIdentifier() => VerifyBreakIntoCharacterParts("Goo42", "Goo", "42"); [Fact] public void BreakIntoCharacterParts_NumberContainingIdentifier() => VerifyBreakIntoCharacterParts("Fog42Bar", "Fog", "42", "Bar"); [Fact] public void BreakIntoCharacterParts_NumberPrefixedIdentifier() { // 42Bar is not a valid identifier in either C# or VB, but it is entirely conceivable the user might be // typing it trying to do a substring match VerifyBreakIntoCharacterParts("42Bar", "42", "Bar"); } [Fact] [WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")] public void BreakIntoWordParts_VerbatimIdentifier() => VerifyBreakIntoWordParts("@int:", "int"); [Fact] [WorkItem(537875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537875")] public void BreakIntoWordParts_AllCapsConstant() => VerifyBreakIntoWordParts("C_STYLE_CONSTANT", "C", "_", "STYLE", "_", "CONSTANT"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_SingleLetterPrefix1() => VerifyBreakIntoWordParts("UInteger", "U", "Integer"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_SingleLetterPrefix2() => VerifyBreakIntoWordParts("IDisposable", "I", "Disposable"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_TwoCharacterCapitalIdentifier() => VerifyBreakIntoWordParts("UIElement", "UI", "Element"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_XDocument() => VerifyBreakIntoWordParts("XDocument", "X", "Document"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_XMLDocument1() => VerifyBreakIntoWordParts("XMLDocument", "XML", "Document"); [Fact] public void BreakIntoWordParts_XMLDocument2() => VerifyBreakIntoWordParts("XmlDocument", "Xml", "Document"); [Fact] public void BreakIntoWordParts_TwoUppercaseCharacters() => VerifyBreakIntoWordParts("SimpleUIElement", "Simple", "UI", "Element"); private static void VerifyBreakIntoWordParts(string original, params string[] parts) => Roslyn.Test.Utilities.AssertEx.Equal(parts, BreakIntoWordParts(original)); private static void VerifyBreakIntoCharacterParts(string original, params string[] parts) => Roslyn.Test.Utilities.AssertEx.Equal(parts, BreakIntoCharacterParts(original)); private const bool CaseSensitive = true; private const bool CaseInsensitive = !CaseSensitive; [Theory] [InlineData("[|Goo|]", "Goo", PatternMatchKind.Exact, CaseSensitive)] [InlineData("[|goo|]", "Goo", PatternMatchKind.Exact, CaseInsensitive)] [InlineData("[|Goo|]", "goo", PatternMatchKind.Exact, CaseInsensitive)] [InlineData("[|Fo|]o", "Fo", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("[|Fog|]Bar", "Fog", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("[|Fo|]o", "fo", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|Fog|]Bar", "fog", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|fog|]BarGoo", "Fog", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|system.ref|]lection", "system.ref", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("Fog[|B|]ar", "b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_[|my|]Button", "my", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("my[|_b|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|my|]button", "my", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_my[|_b|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|myb|]utton", "myb", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|myB|]utton", "myB", PatternMatchKind.NonLowercaseSubstring, CaseSensitive)] [InlineData("my[|_B|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_my[|_B|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_[|myB|]utton", "myb", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("[|AbCd|]xxx[|Ef|]Cd[|Gh|]", "AbCdEfGh", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("A[|BCD|]EFGH", "bcd", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("FogBar[|ChangedEventArgs|]", "changedeventargs", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("Abcdefghij[|EfgHij|]", "efghij", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("[|F|]og[|B|]ar", "FB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|Fo|]g[|B|]ar", "FoB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|_f|]og[|B|]ar", "_fB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|F|]og[|_B|]ar", "F_B", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|F|]og[|B|]ar", "fB", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("Baz[|F|]ogBar[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseSensitive)] [InlineData("[|F|]og[|B|]arBaz", "FB", PatternMatchKind.CamelCasePrefix, CaseSensitive)] [InlineData("[|F|]og_[|B|]ar", "FB", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]ooFlob[|B|]az", "FB", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("Bar[|F|]oo[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseSubstring, CaseSensitive)] [InlineData("BazBar[|F|]oo[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseSubstring, CaseSensitive)] [InlineData("[|Fo|]oBarry[|Bas|]il", "FoBas", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]ogBar[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]og[|_B|]ar", "F_b", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|_F|]og[|B|]ar", "_fB", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|F|]og[|_B|]ar", "f_B", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|Si|]mple[|UI|]Element", "SiUI", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("_[|co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseInsensitive)] [InlineData("Code[|Fi|]xObject[|Pro|]vider", "fipro", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseInsensitive)] [InlineData("[|Co|]de[|Fi|]x[|Pro|]vider", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("Code[|Fi|]x[|Pro|]vider", "fipro", PatternMatchKind.CamelCaseSubstring, CaseInsensitive)] [InlineData("[|Co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|Co|]deFix_[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|C|]ore[|Ofi|]lac[|Pro|]fessional", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|C|]lear[|Ofi|]lac[|Pro|]fessional", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|CO|]DE_FIX_[|PRO|]VIDER", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("my[|_b|]utton", "_B", PatternMatchKind.CamelCaseSubstring, CaseInsensitive)] [InlineData("[|_|]my_[|b|]utton", "_B", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("Com[|bin|]e", "bin", PatternMatchKind.LowercaseSubstring, CaseSensitive)] [InlineData("Combine[|Bin|]ary", "bin", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [WorkItem(51029, "https://github.com/dotnet/roslyn/issues/51029")] internal void TestNonFuzzyMatch( string candidate, string pattern, PatternMatchKind matchKind, bool isCaseSensitive) { var match = TestNonFuzzyMatchCore(candidate, pattern); Assert.NotNull(match); Assert.Equal(matchKind, match.Value.Kind); Assert.Equal(isCaseSensitive, match.Value.IsCaseSensitive); } [Theory] [InlineData("CodeFixObjectProvider", "ficopro")] [InlineData("FogBar", "FBB")] [InlineData("FogBarBaz", "ZZ")] [InlineData("FogBar", "GoooB")] [InlineData("GooActBarCatAlp", "GooAlpBarCat")] // We don't want a lowercase pattern to match *across* a word boundary. [InlineData("AbcdefGhijklmnop", "efghij")] [InlineData("Fog_Bar", "F__B")] [InlineData("FogBarBaz", "FZ")] [InlineData("_mybutton", "myB")] [InlineData("FogBarChangedEventArgs", "changedeventarrrgh")] [InlineData("runtime.native.system", "system.reflection")] public void TestNonFuzzyMatch_NoMatch(string candidate, string pattern) { var match = TestNonFuzzyMatchCore(candidate, pattern); Assert.Null(match); } private static void AssertContainsType(PatternMatchKind type, IEnumerable<PatternMatch> results) => Assert.True(results.Any(r => r.Kind == type)); [Fact] public void MatchMultiWordPattern_ExactWithLowercase() { var match = TryMatchMultiWordPattern("[|AddMetadataReference|]", "addmetadatareference"); AssertContainsType(PatternMatchKind.Exact, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord1() { var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord2() { var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "metadata"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord1() { var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "Add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord2() { var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "Metadata"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter1() { var match = TryMatchMultiWordPattern("[|A|]ddMetadataReference", "A"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter2() { var match = TryMatchMultiWordPattern("Add[|M|]etadataReference", "M"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoLowercaseWords() { var match = TryMatchMultiWordPattern("[|Add|][|Metadata|]Reference", "add metadata"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersSeparateWords() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "A M"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersOneWord() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "AM"); AssertContainsType(PatternMatchKind.CamelCasePrefix, match); } [Fact] public void MatchMultiWordPattern_Mixed1() { var match = TryMatchMultiWordPattern("Add[|Metadata|][|Ref|]erence", "ref Metadata"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [Fact] public void MatchMultiWordPattern_Mixed2() { var match = TryMatchMultiWordPattern("Add[|M|]etadata[|Ref|]erence", "ref M"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [Fact] public void MatchMultiWordPattern_MixedCamelCase() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadata[|Re|]ference", "AMRe"); AssertContainsType(PatternMatchKind.CamelCaseExact, match); } [Fact] public void MatchMultiWordPattern_BlankPattern() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", string.Empty)); [Fact] public void MatchMultiWordPattern_WhitespaceOnlyPattern() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", " ")); [Fact] public void MatchMultiWordPattern_EachWordSeparately1() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately2() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately3() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_MixedCasing1() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "mEta")); [Fact] public void MatchMultiWordPattern_MixedCasing2() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "Data")); [Fact] public void MatchMultiWordPattern_AsteriskSplit() { var match = TryMatchMultiWordPattern("Get[|K|]ey[|W|]ord", "K*W"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")] [Fact] public void MatchMultiWordPattern_LowercaseSubstring1() => Assert.Null(TryMatchMultiWordPattern("Operator", "a")); [WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")] [Fact] public void MatchMultiWordPattern_LowercaseSubstring2() { var match = TryMatchMultiWordPattern("Goo[|A|]ttribute", "a"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); Assert.False(match.First().IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_CultureAwareSingleWordPreferCaseSensitiveExactInsensitive() { var previousCulture = Thread.CurrentThread.CurrentCulture; var turkish = CultureInfo.GetCultureInfo("tr-TR"); Thread.CurrentThread.CurrentCulture = turkish; try { var match = TestNonFuzzyMatchCore("[|ioo|]", "\u0130oo"); // u0130 = Capital I with dot Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } finally { Thread.CurrentThread.CurrentCulture = previousCulture; } } private static ImmutableArray<string> PartListToSubstrings(string identifier, in TemporaryArray<TextSpan> parts) { using var result = TemporaryArray<string>.Empty; foreach (var span in parts) result.Add(identifier.Substring(span.Start, span.Length)); return result.ToImmutableAndClear(); } private static ImmutableArray<string> BreakIntoCharacterParts(string identifier) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddCharacterParts(identifier, ref parts.AsRef()); return PartListToSubstrings(identifier, parts); } private static ImmutableArray<string> BreakIntoWordParts(string identifier) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(identifier, ref parts.AsRef()); return PartListToSubstrings(identifier, parts); } private static PatternMatch? TestNonFuzzyMatchCore(string candidate, string pattern) { MarkupTestFile.GetSpans(candidate, out candidate, out ImmutableArray<TextSpan> spans); var match = PatternMatcher.CreatePatternMatcher(pattern, includeMatchedSpans: true, allowFuzzyMatching: false) .GetFirstMatch(candidate); if (match == null) { Assert.True(spans.Length == 0); } else { Assert.Equal<TextSpan>(match.Value.MatchedSpans, spans); } return match; } private static IEnumerable<PatternMatch> TryMatchMultiWordPattern(string candidate, string pattern) { MarkupTestFile.GetSpans(candidate, out candidate, out ImmutableArray<TextSpan> expectedSpans); using var matches = TemporaryArray<PatternMatch>.Empty; PatternMatcher.CreatePatternMatcher(pattern, includeMatchedSpans: true).AddMatches(candidate, ref matches.AsRef()); if (matches.Count == 0) { Assert.True(expectedSpans.Length == 0); return null; } else { var flattened = new List<TextSpan>(); foreach (var match in matches) flattened.AddRange(match.MatchedSpans); var actualSpans = flattened.OrderBy(s => s.Start).ToList(); Assert.Equal(expectedSpans, actualSpans); return matches.ToImmutableAndClear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class PatternMatcherTests { [Fact] public void BreakIntoCharacterParts_EmptyIdentifier() => VerifyBreakIntoCharacterParts(string.Empty, Array.Empty<string>()); [Fact] public void BreakIntoCharacterParts_SimpleIdentifier() => VerifyBreakIntoCharacterParts("goo", "goo"); [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifier() => VerifyBreakIntoCharacterParts("_goo", "_", "goo"); [Fact] public void BreakIntoCharacterParts_UnderscoredIdentifier() => VerifyBreakIntoCharacterParts("g_oo", "g", "_", "oo"); [Fact] public void BreakIntoCharacterParts_PostfixUnderscoredIdentifier() => VerifyBreakIntoCharacterParts("goo_", "goo", "_"); [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifierWithCapital() => VerifyBreakIntoCharacterParts("_Goo", "_", "Goo"); [Fact] public void BreakIntoCharacterParts_MUnderscorePrefixed() => VerifyBreakIntoCharacterParts("m_goo", "m", "_", "goo"); [Fact] public void BreakIntoCharacterParts_CamelCaseIdentifier() => VerifyBreakIntoCharacterParts("FogBar", "Fog", "Bar"); [Fact] public void BreakIntoCharacterParts_MixedCaseIdentifier() => VerifyBreakIntoCharacterParts("fogBar", "fog", "Bar"); [Fact] public void BreakIntoCharacterParts_TwoCharacterCapitalIdentifier() => VerifyBreakIntoCharacterParts("UIElement", "U", "I", "Element"); [Fact] public void BreakIntoCharacterParts_NumberSuffixedIdentifier() => VerifyBreakIntoCharacterParts("Goo42", "Goo", "42"); [Fact] public void BreakIntoCharacterParts_NumberContainingIdentifier() => VerifyBreakIntoCharacterParts("Fog42Bar", "Fog", "42", "Bar"); [Fact] public void BreakIntoCharacterParts_NumberPrefixedIdentifier() { // 42Bar is not a valid identifier in either C# or VB, but it is entirely conceivable the user might be // typing it trying to do a substring match VerifyBreakIntoCharacterParts("42Bar", "42", "Bar"); } [Fact] [WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")] public void BreakIntoWordParts_VerbatimIdentifier() => VerifyBreakIntoWordParts("@int:", "int"); [Fact] [WorkItem(537875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537875")] public void BreakIntoWordParts_AllCapsConstant() => VerifyBreakIntoWordParts("C_STYLE_CONSTANT", "C", "_", "STYLE", "_", "CONSTANT"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_SingleLetterPrefix1() => VerifyBreakIntoWordParts("UInteger", "U", "Integer"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_SingleLetterPrefix2() => VerifyBreakIntoWordParts("IDisposable", "I", "Disposable"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_TwoCharacterCapitalIdentifier() => VerifyBreakIntoWordParts("UIElement", "UI", "Element"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_XDocument() => VerifyBreakIntoWordParts("XDocument", "X", "Document"); [Fact] [WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")] public void BreakIntoWordParts_XMLDocument1() => VerifyBreakIntoWordParts("XMLDocument", "XML", "Document"); [Fact] public void BreakIntoWordParts_XMLDocument2() => VerifyBreakIntoWordParts("XmlDocument", "Xml", "Document"); [Fact] public void BreakIntoWordParts_TwoUppercaseCharacters() => VerifyBreakIntoWordParts("SimpleUIElement", "Simple", "UI", "Element"); private static void VerifyBreakIntoWordParts(string original, params string[] parts) => Roslyn.Test.Utilities.AssertEx.Equal(parts, BreakIntoWordParts(original)); private static void VerifyBreakIntoCharacterParts(string original, params string[] parts) => Roslyn.Test.Utilities.AssertEx.Equal(parts, BreakIntoCharacterParts(original)); private const bool CaseSensitive = true; private const bool CaseInsensitive = !CaseSensitive; [Theory] [InlineData("[|Goo|]", "Goo", PatternMatchKind.Exact, CaseSensitive)] [InlineData("[|goo|]", "Goo", PatternMatchKind.Exact, CaseInsensitive)] [InlineData("[|Goo|]", "goo", PatternMatchKind.Exact, CaseInsensitive)] [InlineData("[|Fo|]o", "Fo", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("[|Fog|]Bar", "Fog", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("[|Fo|]o", "fo", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|Fog|]Bar", "fog", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|fog|]BarGoo", "Fog", PatternMatchKind.Prefix, CaseInsensitive)] [InlineData("[|system.ref|]lection", "system.ref", PatternMatchKind.Prefix, CaseSensitive)] [InlineData("Fog[|B|]ar", "b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_[|my|]Button", "my", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("my[|_b|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|my|]button", "my", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_my[|_b|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|myb|]utton", "myb", PatternMatchKind.StartOfWordSubstring, CaseSensitive)] [InlineData("_[|myB|]utton", "myB", PatternMatchKind.NonLowercaseSubstring, CaseSensitive)] [InlineData("my[|_B|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_my[|_B|]utton", "_b", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("_[|myB|]utton", "myb", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("[|AbCd|]xxx[|Ef|]Cd[|Gh|]", "AbCdEfGh", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("A[|BCD|]EFGH", "bcd", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("FogBar[|ChangedEventArgs|]", "changedeventargs", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("Abcdefghij[|EfgHij|]", "efghij", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [InlineData("[|F|]og[|B|]ar", "FB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|Fo|]g[|B|]ar", "FoB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|_f|]og[|B|]ar", "_fB", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|F|]og[|_B|]ar", "F_B", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("[|F|]og[|B|]ar", "fB", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("Baz[|F|]ogBar[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseSensitive)] [InlineData("[|F|]og[|B|]arBaz", "FB", PatternMatchKind.CamelCasePrefix, CaseSensitive)] [InlineData("[|F|]og_[|B|]ar", "FB", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]ooFlob[|B|]az", "FB", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("Bar[|F|]oo[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseSubstring, CaseSensitive)] [InlineData("BazBar[|F|]oo[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseSubstring, CaseSensitive)] [InlineData("[|Fo|]oBarry[|Bas|]il", "FoBas", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]ogBar[|F|]oo[|F|]oo", "FFF", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseSensitive)] [InlineData("[|F|]og[|_B|]ar", "F_b", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|_F|]og[|B|]ar", "_fB", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|F|]og[|_B|]ar", "f_B", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|Si|]mple[|UI|]Element", "SiUI", PatternMatchKind.CamelCaseExact, CaseSensitive)] [InlineData("_[|co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseInsensitive)] [InlineData("Code[|Fi|]xObject[|Pro|]vider", "fipro", PatternMatchKind.CamelCaseNonContiguousSubstring, CaseInsensitive)] [InlineData("[|Co|]de[|Fi|]x[|Pro|]vider", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("Code[|Fi|]x[|Pro|]vider", "fipro", PatternMatchKind.CamelCaseSubstring, CaseInsensitive)] [InlineData("[|Co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|co|]deFix[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|Co|]deFix_[|Pro|]vider", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("[|C|]ore[|Ofi|]lac[|Pro|]fessional", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|C|]lear[|Ofi|]lac[|Pro|]fessional", "cofipro", PatternMatchKind.CamelCaseExact, CaseInsensitive)] [InlineData("[|CO|]DE_FIX_[|PRO|]VIDER", "copro", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("my[|_b|]utton", "_B", PatternMatchKind.CamelCaseSubstring, CaseInsensitive)] [InlineData("[|_|]my_[|b|]utton", "_B", PatternMatchKind.CamelCaseNonContiguousPrefix, CaseInsensitive)] [InlineData("Com[|bin|]e", "bin", PatternMatchKind.LowercaseSubstring, CaseSensitive)] [InlineData("Combine[|Bin|]ary", "bin", PatternMatchKind.StartOfWordSubstring, CaseInsensitive)] [WorkItem(51029, "https://github.com/dotnet/roslyn/issues/51029")] internal void TestNonFuzzyMatch( string candidate, string pattern, PatternMatchKind matchKind, bool isCaseSensitive) { var match = TestNonFuzzyMatchCore(candidate, pattern); Assert.NotNull(match); Assert.Equal(matchKind, match.Value.Kind); Assert.Equal(isCaseSensitive, match.Value.IsCaseSensitive); } [Theory] [InlineData("CodeFixObjectProvider", "ficopro")] [InlineData("FogBar", "FBB")] [InlineData("FogBarBaz", "ZZ")] [InlineData("FogBar", "GoooB")] [InlineData("GooActBarCatAlp", "GooAlpBarCat")] // We don't want a lowercase pattern to match *across* a word boundary. [InlineData("AbcdefGhijklmnop", "efghij")] [InlineData("Fog_Bar", "F__B")] [InlineData("FogBarBaz", "FZ")] [InlineData("_mybutton", "myB")] [InlineData("FogBarChangedEventArgs", "changedeventarrrgh")] [InlineData("runtime.native.system", "system.reflection")] public void TestNonFuzzyMatch_NoMatch(string candidate, string pattern) { var match = TestNonFuzzyMatchCore(candidate, pattern); Assert.Null(match); } private static void AssertContainsType(PatternMatchKind type, IEnumerable<PatternMatch> results) => Assert.True(results.Any(r => r.Kind == type)); [Fact] public void MatchMultiWordPattern_ExactWithLowercase() { var match = TryMatchMultiWordPattern("[|AddMetadataReference|]", "addmetadatareference"); AssertContainsType(PatternMatchKind.Exact, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord1() { var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord2() { var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "metadata"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord1() { var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "Add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord2() { var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "Metadata"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter1() { var match = TryMatchMultiWordPattern("[|A|]ddMetadataReference", "A"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter2() { var match = TryMatchMultiWordPattern("Add[|M|]etadataReference", "M"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoLowercaseWords() { var match = TryMatchMultiWordPattern("[|Add|][|Metadata|]Reference", "add metadata"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersSeparateWords() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "A M"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersOneWord() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "AM"); AssertContainsType(PatternMatchKind.CamelCasePrefix, match); } [Fact] public void MatchMultiWordPattern_Mixed1() { var match = TryMatchMultiWordPattern("Add[|Metadata|][|Ref|]erence", "ref Metadata"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [Fact] public void MatchMultiWordPattern_Mixed2() { var match = TryMatchMultiWordPattern("Add[|M|]etadata[|Ref|]erence", "ref M"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [Fact] public void MatchMultiWordPattern_MixedCamelCase() { var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadata[|Re|]ference", "AMRe"); AssertContainsType(PatternMatchKind.CamelCaseExact, match); } [Fact] public void MatchMultiWordPattern_BlankPattern() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", string.Empty)); [Fact] public void MatchMultiWordPattern_WhitespaceOnlyPattern() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", " ")); [Fact] public void MatchMultiWordPattern_EachWordSeparately1() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately2() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately3() { var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); } [Fact] public void MatchMultiWordPattern_MixedCasing1() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "mEta")); [Fact] public void MatchMultiWordPattern_MixedCasing2() => Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "Data")); [Fact] public void MatchMultiWordPattern_AsteriskSplit() { var match = TryMatchMultiWordPattern("Get[|K|]ey[|W|]ord", "K*W"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.StartOfWordSubstring, PatternMatchKind.StartOfWordSubstring })); } [WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")] [Fact] public void MatchMultiWordPattern_LowercaseSubstring1() => Assert.Null(TryMatchMultiWordPattern("Operator", "a")); [WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")] [Fact] public void MatchMultiWordPattern_LowercaseSubstring2() { var match = TryMatchMultiWordPattern("Goo[|A|]ttribute", "a"); AssertContainsType(PatternMatchKind.StartOfWordSubstring, match); Assert.False(match.First().IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_CultureAwareSingleWordPreferCaseSensitiveExactInsensitive() { var previousCulture = Thread.CurrentThread.CurrentCulture; var turkish = CultureInfo.GetCultureInfo("tr-TR"); Thread.CurrentThread.CurrentCulture = turkish; try { var match = TestNonFuzzyMatchCore("[|ioo|]", "\u0130oo"); // u0130 = Capital I with dot Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } finally { Thread.CurrentThread.CurrentCulture = previousCulture; } } private static ImmutableArray<string> PartListToSubstrings(string identifier, in TemporaryArray<TextSpan> parts) { using var result = TemporaryArray<string>.Empty; foreach (var span in parts) result.Add(identifier.Substring(span.Start, span.Length)); return result.ToImmutableAndClear(); } private static ImmutableArray<string> BreakIntoCharacterParts(string identifier) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddCharacterParts(identifier, ref parts.AsRef()); return PartListToSubstrings(identifier, parts); } private static ImmutableArray<string> BreakIntoWordParts(string identifier) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(identifier, ref parts.AsRef()); return PartListToSubstrings(identifier, parts); } private static PatternMatch? TestNonFuzzyMatchCore(string candidate, string pattern) { MarkupTestFile.GetSpans(candidate, out candidate, out ImmutableArray<TextSpan> spans); var match = PatternMatcher.CreatePatternMatcher(pattern, includeMatchedSpans: true, allowFuzzyMatching: false) .GetFirstMatch(candidate); if (match == null) { Assert.True(spans.Length == 0); } else { Assert.Equal<TextSpan>(match.Value.MatchedSpans, spans); } return match; } private static IEnumerable<PatternMatch> TryMatchMultiWordPattern(string candidate, string pattern) { MarkupTestFile.GetSpans(candidate, out candidate, out ImmutableArray<TextSpan> expectedSpans); using var matches = TemporaryArray<PatternMatch>.Empty; PatternMatcher.CreatePatternMatcher(pattern, includeMatchedSpans: true).AddMatches(candidate, ref matches.AsRef()); if (matches.Count == 0) { Assert.True(expectedSpans.Length == 0); return null; } else { var flattened = new List<TextSpan>(); foreach (var match in matches) flattened.AddRange(match.MatchedSpans); var actualSpans = flattened.OrderBy(s => s.Start).ToList(); Assert.Equal(expectedSpans, actualSpans); return matches.ToImmutableAndClear(); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptPredefinedCommandHandlerNames.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptPredefinedCommandHandlerNames { public const string SignatureHelpAfterCompletion = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptPredefinedCommandHandlerNames { public const string SignatureHelpAfterCompletion = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Analyzers/CSharp/Analyzers/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions { #if !CODE_STYLE // Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 [DiagnosticAnalyzer(LanguageNames.CSharp)] #endif internal sealed class CSharpRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer : AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer { protected override string CompilerErrorCodePrefix => "CS"; protected override int CompilerErrorCodeDigitCount => 4; protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override ISemanticFacts SemanticFacts => CSharpSemanticFacts.Instance; protected override (Assembly assembly, string typeName) GetCompilerDiagnosticAnalyzerInfo() => (typeof(SyntaxKind).Assembly, CompilerDiagnosticAnalyzerNames.CSharpCompilerAnalyzerTypeName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions { #if !CODE_STYLE // Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 [DiagnosticAnalyzer(LanguageNames.CSharp)] #endif internal sealed class CSharpRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer : AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer { protected override string CompilerErrorCodePrefix => "CS"; protected override int CompilerErrorCodeDigitCount => 4; protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override ISemanticFacts SemanticFacts => CSharpSemanticFacts.Instance; protected override (Assembly assembly, string typeName) GetCompilerDiagnosticAnalyzerInfo() => (typeof(SyntaxKind).Assembly, CompilerDiagnosticAnalyzerNames.CSharpCompilerAnalyzerTypeName); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/DiaSymReader/Metadata/ISymWriterMetadataProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; namespace Microsoft.DiaSymReader { internal interface ISymWriterMetadataProvider { bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes); bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken); bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; namespace Microsoft.DiaSymReader { internal interface ISymWriterMetadataProvider { bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes); bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken); bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class DefaultArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(DefaultArgumentProvider); [Theory] [InlineData("System.Collections.DictionaryEntry")] public async Task TestDefaultValueIsDefaultLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "default"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("int?")] [InlineData("System.Int32?")] [InlineData("object")] [InlineData("System.Object")] [InlineData("System.Exception")] public async Task TestDefaultValueIsNullLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "null"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("bool", "false")] [InlineData("System.Boolean", "false")] [InlineData("float", "0.0f")] [InlineData("System.Single", "0.0f")] [InlineData("double", "0.0")] [InlineData("System.Double", "0.0")] [InlineData("decimal", "0.0m")] [InlineData("System.Decimal", "0.0m")] [InlineData("char", @"'\\0'")] [InlineData("System.Char", @"'\\0'")] [InlineData("byte", "(byte)0")] [InlineData("System.Byte", "(byte)0")] [InlineData("sbyte", "(sbyte)0")] [InlineData("System.SByte", "(sbyte)0")] [InlineData("short", "(short)0")] [InlineData("System.Int16", "(short)0")] [InlineData("ushort", "(ushort)0")] [InlineData("System.UInt16", "(ushort)0")] [InlineData("int", "0")] [InlineData("System.Int32", "0")] [InlineData("uint", "0U")] [InlineData("System.UInt32", "0U")] [InlineData("long", "0L")] [InlineData("System.Int64", "0L")] [InlineData("ulong", "0UL")] [InlineData("System.UInt64", "0UL")] public async Task TestDefaultValueIsZero(string type, string literalZero) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, literalZero); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class DefaultArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(DefaultArgumentProvider); [Theory] [InlineData("System.Collections.DictionaryEntry")] public async Task TestDefaultValueIsDefaultLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "default"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("int?")] [InlineData("System.Int32?")] [InlineData("object")] [InlineData("System.Object")] [InlineData("System.Exception")] public async Task TestDefaultValueIsNullLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "null"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("bool", "false")] [InlineData("System.Boolean", "false")] [InlineData("float", "0.0f")] [InlineData("System.Single", "0.0f")] [InlineData("double", "0.0")] [InlineData("System.Double", "0.0")] [InlineData("decimal", "0.0m")] [InlineData("System.Decimal", "0.0m")] [InlineData("char", @"'\\0'")] [InlineData("System.Char", @"'\\0'")] [InlineData("byte", "(byte)0")] [InlineData("System.Byte", "(byte)0")] [InlineData("sbyte", "(sbyte)0")] [InlineData("System.SByte", "(sbyte)0")] [InlineData("short", "(short)0")] [InlineData("System.Int16", "(short)0")] [InlineData("ushort", "(ushort)0")] [InlineData("System.UInt16", "(ushort)0")] [InlineData("int", "0")] [InlineData("System.Int32", "0")] [InlineData("uint", "0U")] [InlineData("System.UInt32", "0U")] [InlineData("long", "0L")] [InlineData("System.Int64", "0L")] [InlineData("ulong", "0UL")] [InlineData("System.UInt64", "0UL")] public async Task TestDefaultValueIsZero(string type, string literalZero) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, literalZero); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer : AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer<SyntaxKind, ParenthesizedExpressionSyntax> { protected override SyntaxKind GetSyntaxKind() => SyntaxKind.ParenthesizedExpression; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanRemoveParentheses( ParenthesizedExpressionSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind precedence, out bool clarifiesPrecedence) { return CanRemoveParenthesesHelper( parenthesizedExpression, semanticModel, cancellationToken, out precedence, out clarifiesPrecedence); } public static bool CanRemoveParenthesesHelper( ParenthesizedExpressionSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind parentPrecedenceKind, out bool clarifiesPrecedence) { var result = parenthesizedExpression.CanRemoveParentheses(semanticModel, cancellationToken); if (!result) { parentPrecedenceKind = default; clarifiesPrecedence = false; return false; } var inner = parenthesizedExpression.Expression; var innerPrecedence = inner.GetOperatorPrecedence(); var innerIsSimple = innerPrecedence == OperatorPrecedence.Primary || innerPrecedence == OperatorPrecedence.None; ExpressionSyntax parentExpression; switch (parenthesizedExpression.Parent) { case ConditionalExpressionSyntax _: // If our parent is a conditional, then only remove parens if the inner // expression is a primary. i.e. it's ok to remove any of the following: // // (a()) ? (b.length) : (c[0]) // // But we shouldn't remove parens for anything more complex like: // // ++a ? b + c : d << e // parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return innerIsSimple; case BinaryExpressionSyntax binaryExpression: parentExpression = binaryExpression; break; case IsPatternExpressionSyntax isPatternExpression: // on the left side of an 'x is pat' expression parentExpression = isPatternExpression; break; case ConstantPatternSyntax constantPattern when constantPattern.Parent is IsPatternExpressionSyntax isPatternExpression: // on the right side of an 'x is const_pattern' expression parentExpression = isPatternExpression; break; default: parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } // We're parented by something binary-like. parentPrecedenceKind = CSharpExpressionPrecedenceService.Instance.GetPrecedenceKind(parentExpression); // Precedence is clarified any time we have expression with different precedence // (and the inner expression is not a primary expression). in other words, this // is helps clarify precedence: // // a + (b * c) // // However, this does not: // // a + (b.Length) clarifiesPrecedence = !innerIsSimple && parentExpression.GetOperatorPrecedence() != innerPrecedence; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer : AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer<SyntaxKind, ParenthesizedExpressionSyntax> { protected override SyntaxKind GetSyntaxKind() => SyntaxKind.ParenthesizedExpression; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanRemoveParentheses( ParenthesizedExpressionSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind precedence, out bool clarifiesPrecedence) { return CanRemoveParenthesesHelper( parenthesizedExpression, semanticModel, cancellationToken, out precedence, out clarifiesPrecedence); } public static bool CanRemoveParenthesesHelper( ParenthesizedExpressionSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind parentPrecedenceKind, out bool clarifiesPrecedence) { var result = parenthesizedExpression.CanRemoveParentheses(semanticModel, cancellationToken); if (!result) { parentPrecedenceKind = default; clarifiesPrecedence = false; return false; } var inner = parenthesizedExpression.Expression; var innerPrecedence = inner.GetOperatorPrecedence(); var innerIsSimple = innerPrecedence == OperatorPrecedence.Primary || innerPrecedence == OperatorPrecedence.None; ExpressionSyntax parentExpression; switch (parenthesizedExpression.Parent) { case ConditionalExpressionSyntax _: // If our parent is a conditional, then only remove parens if the inner // expression is a primary. i.e. it's ok to remove any of the following: // // (a()) ? (b.length) : (c[0]) // // But we shouldn't remove parens for anything more complex like: // // ++a ? b + c : d << e // parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return innerIsSimple; case BinaryExpressionSyntax binaryExpression: parentExpression = binaryExpression; break; case IsPatternExpressionSyntax isPatternExpression: // on the left side of an 'x is pat' expression parentExpression = isPatternExpression; break; case ConstantPatternSyntax constantPattern when constantPattern.Parent is IsPatternExpressionSyntax isPatternExpression: // on the right side of an 'x is const_pattern' expression parentExpression = isPatternExpression; break; default: parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } // We're parented by something binary-like. parentPrecedenceKind = CSharpExpressionPrecedenceService.Instance.GetPrecedenceKind(parentExpression); // Precedence is clarified any time we have expression with different precedence // (and the inner expression is not a primary expression). in other words, this // is helps clarify precedence: // // a + (b * c) // // However, this does not: // // a + (b.Length) clarifiesPrecedence = !innerIsSimple && parentExpression.GetOperatorPrecedence() != innerPrecedence; return true; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest2/Recommendations/RestoreKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RestoreKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterHash() => await VerifyAbsenceAsync(@"#$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPragmaWarning() { await VerifyKeywordAsync( @"#pragma warning $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNullable() { await VerifyKeywordAsync( @"#nullable $$"); } [Fact] public async Task TestNotAfterNullableAndNewline() { await VerifyAbsenceAsync(@" #nullable $$ "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RestoreKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterHash() => await VerifyAbsenceAsync(@"#$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPragmaWarning() { await VerifyKeywordAsync( @"#pragma warning $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNullable() { await VerifyKeywordAsync( @"#nullable $$"); } [Fact] public async Task TestNotAfterNullableAndNewline() { await VerifyAbsenceAsync(@" #nullable $$ "); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/AbstractKeyedCodeElement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements identified by a SyntaxNodeKey. /// </summary> public abstract class AbstractKeyedCodeElement : AbstractCodeElement { private SyntaxNodeKey _nodeKey; private readonly string _name; internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKind) { _nodeKey = nodeKey; _name = null; } // This constructor is called for "unknown" code elements. internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _nodeKey = new SyntaxNodeKey(name, -1); _name = name; } internal SyntaxNodeKey NodeKey { get { return _nodeKey; } } internal bool IsUnknown { get { return _nodeKey.Ordinal == -1; } } internal override SyntaxNode LookupNode() => CodeModelService.LookupNode(_nodeKey, GetSyntaxTree()); internal override bool TryLookupNode(out SyntaxNode node) => CodeModelService.TryLookupNode(_nodeKey, GetSyntaxTree(), out node); /// <summary> /// This function re-acquires the key for this code element using the given syntax path. /// </summary> internal void ReacquireNodeKey(SyntaxPath syntaxPath, CancellationToken cancellationToken) { Debug.Assert(syntaxPath != null); if (!syntaxPath.TryResolve(GetSyntaxTree(), cancellationToken, out SyntaxNode node)) { throw Exceptions.ThrowEFail(); } var newNodeKey = CodeModelService.GetNodeKey(node); FileCodeModel.UpdateCodeElementNodeKey(this, _nodeKey, newNodeKey); _nodeKey = newNodeKey; } protected void UpdateNodeAndReacquireNodeKey<T>(Action<SyntaxNode, T> updater, T value, bool trackKinds = true) { FileCodeModel.EnsureEditor(() => { // Sometimes, changing an element can result in needing to update its node key. var node = LookupNode(); var nodePath = new SyntaxPath(node, trackKinds); updater(node, value); ReacquireNodeKey(nodePath, CancellationToken.None); }); } protected override Document DeleteCore(Document document) { var result = base.DeleteCore(document); FileCodeModel.OnCodeElementDeleted(_nodeKey); return result; } protected override string GetName() { if (IsUnknown) { return _name; } return base.GetName(); } protected override void SetName(string value) { FileCodeModel.EnsureEditor(() => { var nodeKeyValidation = new NodeKeyValidation(); nodeKeyValidation.AddFileCodeModel(this.FileCodeModel); var node = LookupNode(); FileCodeModel.UpdateName(node, value); nodeKeyValidation.RestoreKeys(); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements identified by a SyntaxNodeKey. /// </summary> public abstract class AbstractKeyedCodeElement : AbstractCodeElement { private SyntaxNodeKey _nodeKey; private readonly string _name; internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKind) { _nodeKey = nodeKey; _name = null; } // This constructor is called for "unknown" code elements. internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _nodeKey = new SyntaxNodeKey(name, -1); _name = name; } internal SyntaxNodeKey NodeKey { get { return _nodeKey; } } internal bool IsUnknown { get { return _nodeKey.Ordinal == -1; } } internal override SyntaxNode LookupNode() => CodeModelService.LookupNode(_nodeKey, GetSyntaxTree()); internal override bool TryLookupNode(out SyntaxNode node) => CodeModelService.TryLookupNode(_nodeKey, GetSyntaxTree(), out node); /// <summary> /// This function re-acquires the key for this code element using the given syntax path. /// </summary> internal void ReacquireNodeKey(SyntaxPath syntaxPath, CancellationToken cancellationToken) { Debug.Assert(syntaxPath != null); if (!syntaxPath.TryResolve(GetSyntaxTree(), cancellationToken, out SyntaxNode node)) { throw Exceptions.ThrowEFail(); } var newNodeKey = CodeModelService.GetNodeKey(node); FileCodeModel.UpdateCodeElementNodeKey(this, _nodeKey, newNodeKey); _nodeKey = newNodeKey; } protected void UpdateNodeAndReacquireNodeKey<T>(Action<SyntaxNode, T> updater, T value, bool trackKinds = true) { FileCodeModel.EnsureEditor(() => { // Sometimes, changing an element can result in needing to update its node key. var node = LookupNode(); var nodePath = new SyntaxPath(node, trackKinds); updater(node, value); ReacquireNodeKey(nodePath, CancellationToken.None); }); } protected override Document DeleteCore(Document document) { var result = base.DeleteCore(document); FileCodeModel.OnCodeElementDeleted(_nodeKey); return result; } protected override string GetName() { if (IsUnknown) { return _name; } return base.GetName(); } protected override void SetName(string value) { FileCodeModel.EnsureEditor(() => { var nodeKeyValidation = new NodeKeyValidation(); nodeKeyValidation.AddFileCodeModel(this.FileCodeModel); var node = LookupNode(); FileCodeModel.UpdateName(node, value); nodeKeyValidation.RestoreKeys(); }); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. /// This will provide support for options at the global level (i.e. shared among /// all workspaces/services). /// /// In general you should not import this type directly, and should instead get an /// <see cref="IOptionService"/> from <see cref="Workspace.Services"/> /// </summary> internal interface IGlobalOptionService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Applies a set of options, invoking serializers if needed. /// </summary> void SetOptions(OptionSet optionSet); /// <summary> /// Gets force computed serializable options snapshot with prefetched values for the registered options applicable to the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages, IOptionService optionService); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <summary> /// Map an <strong>.editorconfig</strong> key to a corresponding <see cref="IEditorConfigStorageLocation2"/> and /// <see cref="OptionKey"/> that can be used to read and write the value stored in an <see cref="OptionSet"/>. /// </summary> /// <param name="key">The <strong>.editorconfig</strong> key.</param> /// <param name="language">The language to use for the <paramref name="optionKey"/>, if the matching option has /// <see cref="IOption.IsPerLanguage"/> set.</param> /// <param name="storageLocation">The <see cref="IEditorConfigStorageLocation2"/> for the key.</param> /// <param name="optionKey">The <see cref="OptionKey"/> for the key and language.</param> /// <returns><see langword="true"/> if a matching option was found; otherwise, <see langword="false"/>.</returns> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs>? OptionChanged; /// <summary> /// Refreshes the stored value of a serialized option. This should only be called from serializers. /// </summary> void RefreshOption(OptionKey optionKey, object? newValue); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. /// This will provide support for options at the global level (i.e. shared among /// all workspaces/services). /// /// In general you should not import this type directly, and should instead get an /// <see cref="IOptionService"/> from <see cref="Workspace.Services"/> /// </summary> internal interface IGlobalOptionService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Applies a set of options, invoking serializers if needed. /// </summary> void SetOptions(OptionSet optionSet); /// <summary> /// Gets force computed serializable options snapshot with prefetched values for the registered options applicable to the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages, IOptionService optionService); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <summary> /// Map an <strong>.editorconfig</strong> key to a corresponding <see cref="IEditorConfigStorageLocation2"/> and /// <see cref="OptionKey"/> that can be used to read and write the value stored in an <see cref="OptionSet"/>. /// </summary> /// <param name="key">The <strong>.editorconfig</strong> key.</param> /// <param name="language">The language to use for the <paramref name="optionKey"/>, if the matching option has /// <see cref="IOption.IsPerLanguage"/> set.</param> /// <param name="storageLocation">The <see cref="IEditorConfigStorageLocation2"/> for the key.</param> /// <param name="optionKey">The <see cref="OptionKey"/> for the key and language.</param> /// <returns><see langword="true"/> if a matching option was found; otherwise, <see langword="false"/>.</returns> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs>? OptionChanged; /// <summary> /// Refreshes the stored value of a serialized option. This should only be called from serializers. /// </summary> void RefreshOption(OptionKey optionKey, object? newValue); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Xaml/Impl/Features/InlineRename/IXamlRenameInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.InlineRename { internal interface IXamlRenameInfo { /// <summary> /// Whether or not the entity at the selected location can be renamed. /// </summary> bool CanRename { get; } /// <summary> /// Provides the reason that can be displayed to the user if the entity at the selected /// location cannot be renamed. /// </summary> string LocalizedErrorMessage { get; } /// <summary> /// The span of the entity that is being renamed. /// </summary> TextSpan TriggerSpan { get; } /// <summary> /// The short name of the symbol being renamed, for use in displaying information to the user. /// </summary> string DisplayName { get; } /// <summary> /// The full name of the symbol being renamed, for use in displaying information to the user. /// </summary> string FullDisplayName { get; } /// <summary> /// The kind of symbol being renamed, for use in displaying information to the user. /// </summary> SymbolKind Kind { get; } /// <summary> /// Find all locations to be renamed. /// </summary> /// <param name="renameInStrings">Whether or not to rename within strings</param> /// <param name="renameInComments">Whether or not to rename within comments</param> /// <param name="cancellationToken"></param> /// <returns>Returns a list of DocumentSpans</returns> Task<IList<DocumentSpan>> FindRenameLocationsAsync(bool renameInStrings, bool renameInComments, CancellationToken cancellationToken); /// <summary> /// Checks if the new replacement text is valid for this rename operation. /// </summary> /// <returns></returns> bool IsReplacementTextValid(string replacementText); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.InlineRename { internal interface IXamlRenameInfo { /// <summary> /// Whether or not the entity at the selected location can be renamed. /// </summary> bool CanRename { get; } /// <summary> /// Provides the reason that can be displayed to the user if the entity at the selected /// location cannot be renamed. /// </summary> string LocalizedErrorMessage { get; } /// <summary> /// The span of the entity that is being renamed. /// </summary> TextSpan TriggerSpan { get; } /// <summary> /// The short name of the symbol being renamed, for use in displaying information to the user. /// </summary> string DisplayName { get; } /// <summary> /// The full name of the symbol being renamed, for use in displaying information to the user. /// </summary> string FullDisplayName { get; } /// <summary> /// The kind of symbol being renamed, for use in displaying information to the user. /// </summary> SymbolKind Kind { get; } /// <summary> /// Find all locations to be renamed. /// </summary> /// <param name="renameInStrings">Whether or not to rename within strings</param> /// <param name="renameInComments">Whether or not to rename within comments</param> /// <param name="cancellationToken"></param> /// <returns>Returns a list of DocumentSpans</returns> Task<IList<DocumentSpan>> FindRenameLocationsAsync(bool renameInStrings, bool renameInComments, CancellationToken cancellationToken); /// <summary> /// Checks if the new replacement text is valid for this rename operation. /// </summary> /// <returns></returns> bool IsReplacementTextValid(string replacementText); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingTree.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows.Controls; using System.Windows.Input; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { /// <summary> /// Interaction logic for ValueTrackingTree.xaml /// </summary> internal partial class ValueTrackingTree : UserControl { private readonly ValueTrackingTreeViewModel _viewModel; public ValueTrackingTree(ValueTrackingTreeViewModel viewModel) { DataContext = _viewModel = viewModel; InitializeComponent(); } private void ValueTrackingTreeView_PreviewKeyDown(object sender, KeyEventArgs e) { e.Handled = e.Handled || e.Key switch { Key.Down => TrySelectItem(GetNextItem(expandNode: false), navigate: true), Key.Up => TrySelectItem(GetPreviousItem(), navigate: true), Key.F8 => e.KeyboardDevice.Modifiers == ModifierKeys.Shift ? TrySelectItem(GetPreviousItem(), navigate: true) : TrySelectItem(GetNextItem(expandNode: true), navigate: true), Key.Enter => TrySelectItem(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, navigate: true), Key.Right => TrySetExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, true), Key.Left => TrySetExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, false), Key.Space => TryToggleExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase), _ => false }; // Local Functions bool TrySelectItem(TreeViewItemBase? node, bool navigate) { if (node is null) { return false; } SelectItem(node, navigate); return true; } bool TrySetExpanded(TreeViewItemBase? node, bool expanded) { if (node is null) { return false; } node.IsNodeExpanded = expanded; return true; } bool TryToggleExpanded(TreeViewItemBase? node) { return TrySetExpanded(node, node is null ? false : !node.IsNodeExpanded); } } private void ValueTrackingTreeView_MouseClickPreview(object sender, MouseButtonEventArgs e) { if (sender is TreeViewItemBase viewModel && e.ChangedButton == MouseButton.Left) { SelectItem(viewModel, true); e.Handled = true; } } private void SelectItem(TreeViewItemBase? item, bool navigate = false) { _viewModel.SelectedItem = item; if (navigate && item is TreeItemViewModel navigatableItem) { navigatableItem.NavigateTo(); } } private TreeViewItemBase GetNextItem(bool expandNode) { if (ValueTrackingTreeView.SelectedItem is null) { return (TreeViewItemBase)ValueTrackingTreeView.Items[0]; } var item = (TreeViewItemBase)ValueTrackingTreeView.SelectedItem; if (expandNode) { item.IsNodeExpanded = true; } return item.GetNextInTree(); } private TreeViewItemBase GetPreviousItem() { if (ValueTrackingTreeView.SelectedItem is null) { return (TreeViewItemBase)ValueTrackingTreeView.Items[ValueTrackingTreeView.Items.Count - 1]; } var item = (TreeViewItemBase)ValueTrackingTreeView.SelectedItem; return item.GetPreviousInTree(); } private void ValueTrackingTreeView_SelectedItemChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e) { _viewModel.SelectedItem = ValueTrackingTreeView.SelectedItem as TreeViewItemBase; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows.Controls; using System.Windows.Input; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { /// <summary> /// Interaction logic for ValueTrackingTree.xaml /// </summary> internal partial class ValueTrackingTree : UserControl { private readonly ValueTrackingTreeViewModel _viewModel; public ValueTrackingTree(ValueTrackingTreeViewModel viewModel) { DataContext = _viewModel = viewModel; InitializeComponent(); } private void ValueTrackingTreeView_PreviewKeyDown(object sender, KeyEventArgs e) { e.Handled = e.Handled || e.Key switch { Key.Down => TrySelectItem(GetNextItem(expandNode: false), navigate: true), Key.Up => TrySelectItem(GetPreviousItem(), navigate: true), Key.F8 => e.KeyboardDevice.Modifiers == ModifierKeys.Shift ? TrySelectItem(GetPreviousItem(), navigate: true) : TrySelectItem(GetNextItem(expandNode: true), navigate: true), Key.Enter => TrySelectItem(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, navigate: true), Key.Right => TrySetExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, true), Key.Left => TrySetExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase, false), Key.Space => TryToggleExpanded(ValueTrackingTreeView.SelectedItem as TreeViewItemBase), _ => false }; // Local Functions bool TrySelectItem(TreeViewItemBase? node, bool navigate) { if (node is null) { return false; } SelectItem(node, navigate); return true; } bool TrySetExpanded(TreeViewItemBase? node, bool expanded) { if (node is null) { return false; } node.IsNodeExpanded = expanded; return true; } bool TryToggleExpanded(TreeViewItemBase? node) { return TrySetExpanded(node, node is null ? false : !node.IsNodeExpanded); } } private void ValueTrackingTreeView_MouseClickPreview(object sender, MouseButtonEventArgs e) { if (sender is TreeViewItemBase viewModel && e.ChangedButton == MouseButton.Left) { SelectItem(viewModel, true); e.Handled = true; } } private void SelectItem(TreeViewItemBase? item, bool navigate = false) { _viewModel.SelectedItem = item; if (navigate && item is TreeItemViewModel navigatableItem) { navigatableItem.NavigateTo(); } } private TreeViewItemBase GetNextItem(bool expandNode) { if (ValueTrackingTreeView.SelectedItem is null) { return (TreeViewItemBase)ValueTrackingTreeView.Items[0]; } var item = (TreeViewItemBase)ValueTrackingTreeView.SelectedItem; if (expandNode) { item.IsNodeExpanded = true; } return item.GetNextInTree(); } private TreeViewItemBase GetPreviousItem() { if (ValueTrackingTreeView.SelectedItem is null) { return (TreeViewItemBase)ValueTrackingTreeView.Items[ValueTrackingTreeView.Items.Count - 1]; } var item = (TreeViewItemBase)ValueTrackingTreeView.SelectedItem; return item.GetPreviousInTree(); } private void ValueTrackingTreeView_SelectedItemChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e) { _viewModel.SelectedItem = ValueTrackingTreeView.SelectedItem as TreeViewItemBase; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenScriptTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class CodeGenScriptTests : CSharpTestBase { [Fact] public void AnonymousTypes_TopLevelVar() { string test = @" using System; var o = new { a = 1 }; Console.WriteLine(o.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_TopLevel_Object() { string test = @" using System; object o = new { a = 1 }; Console.WriteLine(o.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_TopLevel_NoLocal() { string test = @" using System; Console.WriteLine(new { a = 1 }.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_NestedClass_Method() { string test = @" using System; class CLS { public void M() { Console.WriteLine(new { a = 1 }.ToString()); } } new CLS().M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_NestedClass_MethodParamDefValue() { string test = @" using System; class CLS { public void M(object p = new { a = 1 }) { Console.WriteLine(""OK""); } } new CLS().M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (5,30): error CS1736: Default parameter value for 'p' must be a compile-time constant // public void M(object p = new { a = 1 }) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new { a = 1 }").WithArguments("p")); } [Fact] public void AnonymousTypes_TopLevel_MethodParamDefValue() { string test = @" using System; public void M(object p = new { a = 1 }) { Console.WriteLine(""OK""); } M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (4,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // public void M(object p = new { a = 1 }) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new { a = 1 }").WithArguments("p")); } [Fact] public void AnonymousTypes_TopLevel_MethodAttribute() { string test = @" using System; class A: Attribute { public object P; } [A(P = new { a = 1 })] public void M() { Console.WriteLine(""OK""); } M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (9,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(P = new { a = 1 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new { a = 1 }")); } [Fact] public void AnonymousTypes_NestedTypeAttribute() { string test = @" using System; class A: Attribute { public object P; } [A(P = new { a = 1 })] class CLS { } "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (9,8): error CS0836: Cannot use anonymous type in a constant expression // [A(P = new { a = 1 })] Diagnostic(ErrorCode.ERR_AnonymousTypeNotAvailable, "new")); } [Fact] public void CompilationChain_AnonymousTypeTemplates() { var s0 = CreateSubmission("var x = new { a = 1 }; "); var sx = CreateSubmission("var y = new { b = 2 }; ", previous: s0); var s1 = CreateSubmission("var y = new { b = new { a = 3 } };", previous: s0); var s2 = CreateSubmission("x = y.b; ", previous: s1); s2.VerifyDiagnostics(); s2.EmitToArray(); Assert.True(s2.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(0, s2.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.True(s1.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s1.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.True(s0.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s0.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.False(sx.AnonymousTypeManager.AreTemplatesSealed); } [Fact] public void CompilationChain_DynamicSiteDelegates() { // TODO: references should be inherited MetadataReference[] references = { SystemCoreRef, CSharpRef }; var s0 = CreateSubmission("var i = 1; dynamic d = null; d.m(ref i);", references); var sx = CreateSubmission("var i = 1; dynamic d = null; d.m(ref i, ref i);", references, previous: s0); var s1 = CreateSubmission("var i = 1; dynamic d = null; d.m(out i);", references, previous: s0); s1.VerifyDiagnostics(); s1.EmitToArray(); // no new delegates should have been created: Assert.True(s1.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(0, s1.AnonymousTypeManager.GetAllCreatedTemplates().Length); // delegate for (ref) Assert.True(s0.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s0.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.False(sx.AnonymousTypeManager.AreTemplatesSealed); } [Fact] public void Submissions_EmitToPeStream() { var s0 = CreateSubmission("int a = 1;"); var s11 = CreateSubmission("a + 1", previous: s0); var s12 = CreateSubmission("a + 2", previous: s0); s11.VerifyEmitDiagnostics(); s12.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Generic() { var c0 = CreateSubmission(@" public interface I<T> { void m<TT>(T x, TT y); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { public void m<TT>(int x, TT y) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit_GenericMethod() { var c0 = CreateSubmission(@" public interface I<T> { void m<S>(T x, S y); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m<S>(int x, S y) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" public interface I<T> { void m(T x); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m(int x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I<T> { void m(byte x); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m(byte x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void GenericInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I<T> { void m(byte x); } abstract public class C : I<int> { void I<int>.m(byte x) { } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I { void m(byte x); } "); var c1 = CreateSubmission(@" abstract public class C : I { void I.m(byte x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionNestedGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" class C<T> { public interface I { void m(T x); } } "); var c1 = CreateSubmission(@" abstract public class D : C<int>.I { void C<int>.I.m(int x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void NestedGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" class C<T> { public interface I { void m(T x); } } abstract public class D : C<int>.I { void C<int>.I.m(int x) { } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void ExternalInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" using System.Collections; using System.Collections.Generic; abstract public class C : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void AbstractAccessors() { var c0 = CreateSubmission(@" public abstract class C { public abstract event System.Action vEv; public abstract int prop { get; set; } } "); c0.VerifyEmitDiagnostics(); } [Fact] public void ExprStmtWithMethodCall() { var s0 = CreateSubmission("int Goo() { return 2;}"); var s1 = CreateSubmission("(4 + 5) * Goo()", previous: s0); s0.VerifyEmitDiagnostics(); s1.VerifyEmitDiagnostics(); } /// <summary> /// The script entry point should complete synchronously. /// </summary> [WorkItem(4495, "https://github.com/dotnet/roslyn/issues/4495")] [ConditionalFact(typeof(DesktopOnly))] public void ScriptEntryPoint() { var source = @"{ await System.Threading.Tasks.Task.Delay(100); System.Console.Write(""complete""); }"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"complete"); var methodData = verifier.TestData.GetMethodData("<Initialize>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 57 (0x39) .maxstack 2 .locals init (<<Initialize>>d__0 V_0) IL_0000: newobj ""<<Initialize>>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""Script <<Initialize>>d__0.<>4__this"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int <<Initialize>>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<<<Initialize>>d__0>(ref <<Initialize>>d__0)"" IL_002c: nop IL_002d: ldloc.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0033: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0038: ret }"); methodData = verifier.TestData.GetMethodData("<Main>"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 1 .locals init (System.Runtime.CompilerServices.TaskAwaiter<object> V_0) IL_0000: newobj "".ctor()"" IL_0005: callvirt ""System.Threading.Tasks.Task<object> <Initialize>()"" IL_000a: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<object> System.Threading.Tasks.Task<object>.GetAwaiter()"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: call ""object System.Runtime.CompilerServices.TaskAwaiter<object>.GetResult()"" IL_0017: pop IL_0018: ret }"); } [ConditionalFact(typeof(DesktopOnly))] public void SubmissionEntryPoint() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"{ await System.Threading.Tasks.Task.Delay(100); System.Console.Write(""complete""); }"; var s0 = CSharpCompilation.CreateScriptCompilation( "s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); var verifier = CompileAndVerify(s0, verify: Verification.Fails); var methodData = verifier.TestData.GetMethodData("<Initialize>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 57 (0x39) .maxstack 2 .locals init (<<Initialize>>d__0 V_0) IL_0000: newobj ""<<Initialize>>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""Script <<Initialize>>d__0.<>4__this"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int <<Initialize>>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<<<Initialize>>d__0>(ref <<Initialize>>d__0)"" IL_002c: nop IL_002d: ldloc.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0033: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0038: ret }"); methodData = verifier.TestData.GetMethodData("<Factory>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj "".ctor(object[])"" IL_0006: callvirt ""System.Threading.Tasks.Task<object> <Initialize>()"" IL_000b: ret }"); } [Fact] public void ScriptEntryPoint_MissingMethods() { var source = "System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyEmitDiagnostics( // error CS1061: 'Task<object>' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'Task<object>' could be found (are you missing a using directive or an assembly reference?) // Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "").WithArguments("System.Threading.Tasks.Task<object>", "GetAwaiter").WithLocation(1, 1), // (1,1): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1' is not defined or imported // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Create' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Create").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Task' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Task").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(1, 1)); } [Fact] public void ExplicitImplementation() { string test = @" interface I1 { void M(); } void I1.M() {} "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (7,6): error CS0540: 'I1.M()': containing type does not implement interface 'I1' // void I1.M() {} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M()", "I1").WithLocation(7, 6) ); var s = CreateSubmission(test); s.VerifyDiagnostics( // (7,9): error CS0541: 'M()': explicit interface declaration can only be declared in a class, record, struct or interface // void I1.M() {} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, "M").WithArguments("M()").WithLocation(7, 9) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class CodeGenScriptTests : CSharpTestBase { [Fact] public void AnonymousTypes_TopLevelVar() { string test = @" using System; var o = new { a = 1 }; Console.WriteLine(o.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_TopLevel_Object() { string test = @" using System; object o = new { a = 1 }; Console.WriteLine(o.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_TopLevel_NoLocal() { string test = @" using System; Console.WriteLine(new { a = 1 }.ToString()); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_NestedClass_Method() { string test = @" using System; class CLS { public void M() { Console.WriteLine(new { a = 1 }.ToString()); } } new CLS().M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); CompileAndVerify( CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), references: new[] { SystemCoreRef }), expectedOutput: "{ a = 1 }" ); } [Fact] public void AnonymousTypes_NestedClass_MethodParamDefValue() { string test = @" using System; class CLS { public void M(object p = new { a = 1 }) { Console.WriteLine(""OK""); } } new CLS().M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (5,30): error CS1736: Default parameter value for 'p' must be a compile-time constant // public void M(object p = new { a = 1 }) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new { a = 1 }").WithArguments("p")); } [Fact] public void AnonymousTypes_TopLevel_MethodParamDefValue() { string test = @" using System; public void M(object p = new { a = 1 }) { Console.WriteLine(""OK""); } M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (4,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // public void M(object p = new { a = 1 }) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new { a = 1 }").WithArguments("p")); } [Fact] public void AnonymousTypes_TopLevel_MethodAttribute() { string test = @" using System; class A: Attribute { public object P; } [A(P = new { a = 1 })] public void M() { Console.WriteLine(""OK""); } M(); "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (9,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(P = new { a = 1 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new { a = 1 }")); } [Fact] public void AnonymousTypes_NestedTypeAttribute() { string test = @" using System; class A: Attribute { public object P; } [A(P = new { a = 1 })] class CLS { } "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (9,8): error CS0836: Cannot use anonymous type in a constant expression // [A(P = new { a = 1 })] Diagnostic(ErrorCode.ERR_AnonymousTypeNotAvailable, "new")); } [Fact] public void CompilationChain_AnonymousTypeTemplates() { var s0 = CreateSubmission("var x = new { a = 1 }; "); var sx = CreateSubmission("var y = new { b = 2 }; ", previous: s0); var s1 = CreateSubmission("var y = new { b = new { a = 3 } };", previous: s0); var s2 = CreateSubmission("x = y.b; ", previous: s1); s2.VerifyDiagnostics(); s2.EmitToArray(); Assert.True(s2.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(0, s2.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.True(s1.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s1.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.True(s0.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s0.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.False(sx.AnonymousTypeManager.AreTemplatesSealed); } [Fact] public void CompilationChain_DynamicSiteDelegates() { // TODO: references should be inherited MetadataReference[] references = { SystemCoreRef, CSharpRef }; var s0 = CreateSubmission("var i = 1; dynamic d = null; d.m(ref i);", references); var sx = CreateSubmission("var i = 1; dynamic d = null; d.m(ref i, ref i);", references, previous: s0); var s1 = CreateSubmission("var i = 1; dynamic d = null; d.m(out i);", references, previous: s0); s1.VerifyDiagnostics(); s1.EmitToArray(); // no new delegates should have been created: Assert.True(s1.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(0, s1.AnonymousTypeManager.GetAllCreatedTemplates().Length); // delegate for (ref) Assert.True(s0.AnonymousTypeManager.AreTemplatesSealed); Assert.Equal(1, s0.AnonymousTypeManager.GetAllCreatedTemplates().Length); Assert.False(sx.AnonymousTypeManager.AreTemplatesSealed); } [Fact] public void Submissions_EmitToPeStream() { var s0 = CreateSubmission("int a = 1;"); var s11 = CreateSubmission("a + 1", previous: s0); var s12 = CreateSubmission("a + 2", previous: s0); s11.VerifyEmitDiagnostics(); s12.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Generic() { var c0 = CreateSubmission(@" public interface I<T> { void m<TT>(T x, TT y); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { public void m<TT>(int x, TT y) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit_GenericMethod() { var c0 = CreateSubmission(@" public interface I<T> { void m<S>(T x, S y); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m<S>(int x, S y) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" public interface I<T> { void m(T x); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m(int x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionGenericInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I<T> { void m(byte x); } "); var c1 = CreateSubmission(@" abstract public class C : I<int> { void I<int>.m(byte x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void GenericInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I<T> { void m(byte x); } abstract public class C : I<int> { void I<int>.m(byte x) { } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionInterfaceImplementation_Explicit_NoGenericParametersInSignature() { var c0 = CreateSubmission(@" public interface I { void m(byte x); } "); var c1 = CreateSubmission(@" abstract public class C : I { void I.m(byte x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void CrossSubmissionNestedGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" class C<T> { public interface I { void m(T x); } } "); var c1 = CreateSubmission(@" abstract public class D : C<int>.I { void C<int>.I.m(int x) { } }", previous: c0); c0.VerifyEmitDiagnostics(); c1.VerifyEmitDiagnostics(); } [Fact] public void NestedGenericInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" class C<T> { public interface I { void m(T x); } } abstract public class D : C<int>.I { void C<int>.I.m(int x) { } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void ExternalInterfaceImplementation_Explicit() { var c0 = CreateSubmission(@" using System.Collections; using System.Collections.Generic; abstract public class C : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"); c0.VerifyEmitDiagnostics(); } [Fact] public void AbstractAccessors() { var c0 = CreateSubmission(@" public abstract class C { public abstract event System.Action vEv; public abstract int prop { get; set; } } "); c0.VerifyEmitDiagnostics(); } [Fact] public void ExprStmtWithMethodCall() { var s0 = CreateSubmission("int Goo() { return 2;}"); var s1 = CreateSubmission("(4 + 5) * Goo()", previous: s0); s0.VerifyEmitDiagnostics(); s1.VerifyEmitDiagnostics(); } /// <summary> /// The script entry point should complete synchronously. /// </summary> [WorkItem(4495, "https://github.com/dotnet/roslyn/issues/4495")] [ConditionalFact(typeof(DesktopOnly))] public void ScriptEntryPoint() { var source = @"{ await System.Threading.Tasks.Task.Delay(100); System.Console.Write(""complete""); }"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"complete"); var methodData = verifier.TestData.GetMethodData("<Initialize>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 57 (0x39) .maxstack 2 .locals init (<<Initialize>>d__0 V_0) IL_0000: newobj ""<<Initialize>>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""Script <<Initialize>>d__0.<>4__this"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int <<Initialize>>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<<<Initialize>>d__0>(ref <<Initialize>>d__0)"" IL_002c: nop IL_002d: ldloc.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0033: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0038: ret }"); methodData = verifier.TestData.GetMethodData("<Main>"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 1 .locals init (System.Runtime.CompilerServices.TaskAwaiter<object> V_0) IL_0000: newobj "".ctor()"" IL_0005: callvirt ""System.Threading.Tasks.Task<object> <Initialize>()"" IL_000a: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<object> System.Threading.Tasks.Task<object>.GetAwaiter()"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: call ""object System.Runtime.CompilerServices.TaskAwaiter<object>.GetResult()"" IL_0017: pop IL_0018: ret }"); } [ConditionalFact(typeof(DesktopOnly))] public void SubmissionEntryPoint() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"{ await System.Threading.Tasks.Task.Delay(100); System.Console.Write(""complete""); }"; var s0 = CSharpCompilation.CreateScriptCompilation( "s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); var verifier = CompileAndVerify(s0, verify: Verification.Fails); var methodData = verifier.TestData.GetMethodData("<Initialize>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 57 (0x39) .maxstack 2 .locals init (<<Initialize>>d__0 V_0) IL_0000: newobj ""<<Initialize>>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""Script <<Initialize>>d__0.<>4__this"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int <<Initialize>>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<<<Initialize>>d__0>(ref <<Initialize>>d__0)"" IL_002c: nop IL_002d: ldloc.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0033: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0038: ret }"); methodData = verifier.TestData.GetMethodData("<Factory>"); Assert.Equal("System.Threading.Tasks.Task<object>", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj "".ctor(object[])"" IL_0006: callvirt ""System.Threading.Tasks.Task<object> <Initialize>()"" IL_000b: ret }"); } [Fact] public void ScriptEntryPoint_MissingMethods() { var source = "System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyEmitDiagnostics( // error CS1061: 'Task<object>' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'Task<object>' could be found (are you missing a using directive or an assembly reference?) // Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "").WithArguments("System.Threading.Tasks.Task<object>", "GetAwaiter").WithLocation(1, 1), // (1,1): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1' is not defined or imported // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Create' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Create").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Task' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Task").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(1, 1), // (1,1): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "System.Console.WriteLine(1);").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(1, 1)); } [Fact] public void ExplicitImplementation() { string test = @" interface I1 { void M(); } void I1.M() {} "; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); var compilation = CreateCompilationWithMscorlib45( new[] { tree }, options: TestOptions.ReleaseExe.WithScriptClassName("Script")); compilation.VerifyDiagnostics( // (7,6): error CS0540: 'I1.M()': containing type does not implement interface 'I1' // void I1.M() {} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("I1.M()", "I1").WithLocation(7, 6) ); var s = CreateSubmission(test); s.VerifyDiagnostics( // (7,9): error CS0541: 'M()': explicit interface declaration can only be declared in a class, record, struct or interface // void I1.M() {} Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, "M").WithArguments("M()").WithLocation(7, 9) ); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.FloatingTC.cs
// Licensed to the .NET Foundation under one or more 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.CSharp { internal static partial class ValueSetFactory { /// <summary> /// A type class providing primitive operations needed to support a value set for a floating-point type. /// </summary> private interface FloatingTC<T> : INumericTC<T> { /// <summary> /// A "not a number" value for the floating-point type <typeparamref name="T"/>. /// All NaN values are treated as equivalent. /// </summary> T NaN { 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. namespace Microsoft.CodeAnalysis.CSharp { internal static partial class ValueSetFactory { /// <summary> /// A type class providing primitive operations needed to support a value set for a floating-point type. /// </summary> private interface FloatingTC<T> : INumericTC<T> { /// <summary> /// A "not a number" value for the floating-point type <typeparamref name="T"/>. /// All NaN values are treated as equivalent. /// </summary> T NaN { get; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Test/Core/Platform/Desktop/RuntimeModuleData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Roslyn.Test.Utilities.Desktop { [Serializable] public struct RuntimeModuleDataId : ISerializable { public ModuleDataId Id { get; } public RuntimeModuleDataId(ModuleDataId id) { Id = id; } private RuntimeModuleDataId(SerializationInfo info, StreamingContext context) { var simpleName = info.GetString(nameof(Id.SimpleName)); var fullName = info.GetString(nameof(Id.FullName)); var mvid = (Guid)info.GetValue(nameof(Id.Mvid), typeof(Guid)); Id = new ModuleDataId(simpleName, fullName, mvid); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(Id.SimpleName), Id.SimpleName); info.AddValue(nameof(Id.FullName), Id.FullName); info.AddValue(nameof(Id.Mvid), Id.Mvid); } } [Serializable, DebuggerDisplay("{GetDebuggerDisplay()}")] public sealed class RuntimeModuleData : ISerializable { public ModuleData Data { get; } public RuntimeModuleData(ModuleData data) { Data = data; } private RuntimeModuleData(SerializationInfo info, StreamingContext context) { var id = (RuntimeModuleDataId)info.GetValue(nameof(ModuleData.Id), typeof(RuntimeModuleDataId)); var kind = (OutputKind)info.GetInt32(nameof(ModuleData.Kind)); var image = info.GetByteArray(nameof(ModuleData.Image)); var pdb = info.GetByteArray(nameof(ModuleData.Pdb)); var inMemoryModule = info.GetBoolean(nameof(ModuleData.InMemoryModule)); Data = new ModuleData(id.Id, kind, image, pdb, inMemoryModule); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(ModuleData.Id), new RuntimeModuleDataId(Data.Id)); info.AddValue(nameof(ModuleData.Kind), (int)Data.Kind); info.AddByteArray(nameof(ModuleData.Image), Data.Image); info.AddByteArray(nameof(ModuleData.Pdb), Data.Pdb); info.AddValue(nameof(ModuleData.InMemoryModule), Data.InMemoryModule); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Roslyn.Test.Utilities.Desktop { [Serializable] public struct RuntimeModuleDataId : ISerializable { public ModuleDataId Id { get; } public RuntimeModuleDataId(ModuleDataId id) { Id = id; } private RuntimeModuleDataId(SerializationInfo info, StreamingContext context) { var simpleName = info.GetString(nameof(Id.SimpleName)); var fullName = info.GetString(nameof(Id.FullName)); var mvid = (Guid)info.GetValue(nameof(Id.Mvid), typeof(Guid)); Id = new ModuleDataId(simpleName, fullName, mvid); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(Id.SimpleName), Id.SimpleName); info.AddValue(nameof(Id.FullName), Id.FullName); info.AddValue(nameof(Id.Mvid), Id.Mvid); } } [Serializable, DebuggerDisplay("{GetDebuggerDisplay()}")] public sealed class RuntimeModuleData : ISerializable { public ModuleData Data { get; } public RuntimeModuleData(ModuleData data) { Data = data; } private RuntimeModuleData(SerializationInfo info, StreamingContext context) { var id = (RuntimeModuleDataId)info.GetValue(nameof(ModuleData.Id), typeof(RuntimeModuleDataId)); var kind = (OutputKind)info.GetInt32(nameof(ModuleData.Kind)); var image = info.GetByteArray(nameof(ModuleData.Image)); var pdb = info.GetByteArray(nameof(ModuleData.Pdb)); var inMemoryModule = info.GetBoolean(nameof(ModuleData.InMemoryModule)); Data = new ModuleData(id.Id, kind, image, pdb, inMemoryModule); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(ModuleData.Id), new RuntimeModuleDataId(Data.Id)); info.AddValue(nameof(ModuleData.Kind), (int)Data.Kind); info.AddByteArray(nameof(ModuleData.Image), Data.Image); info.AddByteArray(nameof(ModuleData.Pdb), Data.Pdb); info.AddValue(nameof(ModuleData.InMemoryModule), Data.InMemoryModule); } } } #endif
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/PublicModel/SourceAssemblySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class SourceAssemblySymbol : AssemblySymbol, ISourceAssemblySymbol { private readonly Symbols.SourceAssemblySymbol _underlying; public SourceAssemblySymbol(Symbols.SourceAssemblySymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying; internal override CSharp.Symbol UnderlyingSymbol => _underlying; Compilation ISourceAssemblySymbol.Compilation => _underlying.DeclaringCompilation; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class SourceAssemblySymbol : AssemblySymbol, ISourceAssemblySymbol { private readonly Symbols.SourceAssemblySymbol _underlying; public SourceAssemblySymbol(Symbols.SourceAssemblySymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying; internal override CSharp.Symbol UnderlyingSymbol => _underlying; Compilation ISourceAssemblySymbol.Compilation => _underlying.DeclaringCompilation; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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_INoPiaObjectCreationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ y }') Initializers(1): IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'ITest33') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (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) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { P = y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ P = y }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'P') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33()/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { y }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: null IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33 { y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33 { y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { P = y }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { P = y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... { P = y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... { P = y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33()') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') Right: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_04() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(object x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, object y1, object y2) { x = new ITest33 { y1 ?? y2 }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" 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: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 ... y1 ?? y2 }') Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [3] .locals {R3} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation (virtual void ITest33.Add(System.Object x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y1 ?? y2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y1 ?? y2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1 ?? y2') 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[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... y1 ?? y2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... y1 ?? y2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: 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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_INoPiaObjectCreationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ y }') Initializers(1): IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'ITest33') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (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) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { P = y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ P = y }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'P') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33()/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { y }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: null IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33 { y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33 { y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { P = y }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { P = y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... { P = y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... { P = y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33()') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') Right: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_04() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(object x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, object y1, object y2) { x = new ITest33 { y1 ?? y2 }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" 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: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 ... y1 ?? y2 }') Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [3] .locals {R3} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation (virtual void ITest33.Add(System.Object x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y1 ?? y2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y1 ?? y2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1 ?? y2') 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[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... y1 ?? y2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... y1 ?? y2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalOverloadsCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public class ExternalOverloadsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, ExternalCodeFunction parent, ProjectId projectId) { var collection = new ExternalOverloadsCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalOverloadsCollection( CodeModelState state, ExternalCodeFunction parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private ExternalCodeFunction ParentElement { get { return (ExternalCodeFunction)Parent; } } private ImmutableArray<EnvDTE.CodeElement> EnumerateOverloads() { var symbol = (IMethodSymbol)ParentElement.LookupSymbol(); // Only methods and constructors can be overloaded. However, all functions // can successfully return a collection of overloaded functions; if not // really overloaded, the collection contains just the original function. if (symbol.MethodKind != MethodKind.Ordinary && symbol.MethodKind != MethodKind.Constructor) { return ImmutableArray.Create((EnvDTE.CodeElement)Parent); } var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(); foreach (var method in symbol.ContainingType.GetMembers(symbol.Name)) { if (method.Kind != SymbolKind.Method) { continue; } var element = ExternalCodeFunction.Create(this.State, _projectId, (IMethodSymbol)method); if (element != null) { overloadsBuilder.Add((EnvDTE.CodeElement)element); } } return overloadsBuilder.ToImmutableAndFree(); } public override int Count { get { return EnumerateOverloads().Length; } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { if (index >= 0 && index < EnumerateOverloads().Length) { element = EnumerateOverloads()[index]; return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { element = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public class ExternalOverloadsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, ExternalCodeFunction parent, ProjectId projectId) { var collection = new ExternalOverloadsCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalOverloadsCollection( CodeModelState state, ExternalCodeFunction parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private ExternalCodeFunction ParentElement { get { return (ExternalCodeFunction)Parent; } } private ImmutableArray<EnvDTE.CodeElement> EnumerateOverloads() { var symbol = (IMethodSymbol)ParentElement.LookupSymbol(); // Only methods and constructors can be overloaded. However, all functions // can successfully return a collection of overloaded functions; if not // really overloaded, the collection contains just the original function. if (symbol.MethodKind != MethodKind.Ordinary && symbol.MethodKind != MethodKind.Constructor) { return ImmutableArray.Create((EnvDTE.CodeElement)Parent); } var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(); foreach (var method in symbol.ContainingType.GetMembers(symbol.Name)) { if (method.Kind != SymbolKind.Method) { continue; } var element = ExternalCodeFunction.Create(this.State, _projectId, (IMethodSymbol)method); if (element != null) { overloadsBuilder.Add((EnvDTE.CodeElement)element); } } return overloadsBuilder.ToImmutableAndFree(); } public override int Count { get { return EnumerateOverloads().Length; } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { if (index >= 0 && index < EnumerateOverloads().Length) { element = EnumerateOverloads()[index]; return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { element = null; return false; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/OperatorAnalysisResultKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum OperatorAnalysisResultKind : byte { Undefined = 0, Inapplicable, Worse, Applicable, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum OperatorAnalysisResultKind : byte { Undefined = 0, Inapplicable, Worse, Applicable, } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel_RegionAnalysisContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private RegionAnalysisContext RegionAnalysisContext(ExpressionSyntax expression) { while (expression.Kind() == SyntaxKind.ParenthesizedExpression) expression = ((ParenthesizedExpressionSyntax)expression).Expression; var memberModel = GetMemberModel(expression); if (memberModel == null) { // Recover from error cases var node = new BoundBadStatement(expression, ImmutableArray<BoundNode>.Empty, hasErrors: true); return new RegionAnalysisContext(Compilation, null, node, node, node); } Symbol member; BoundNode boundNode = GetBoundRoot(memberModel, out member); var first = memberModel.GetUpperBoundNode(expression, promoteToBindable: true); var last = first; return new RegionAnalysisContext(this.Compilation, member, boundNode, first, last); } private RegionAnalysisContext RegionAnalysisContext(StatementSyntax firstStatement, StatementSyntax lastStatement) { var memberModel = GetMemberModel(firstStatement); if (memberModel == null) { // Recover from error cases var node = new BoundBadStatement(firstStatement, ImmutableArray<BoundNode>.Empty, hasErrors: true); return new RegionAnalysisContext(Compilation, null, node, node, node); } Symbol member; BoundNode boundNode = GetBoundRoot(memberModel, out member); var first = memberModel.GetUpperBoundNode(firstStatement, promoteToBindable: true); var last = memberModel.GetUpperBoundNode(lastStatement, promoteToBindable: true); return new RegionAnalysisContext(Compilation, member, boundNode, first, last); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private RegionAnalysisContext RegionAnalysisContext(ExpressionSyntax expression) { while (expression.Kind() == SyntaxKind.ParenthesizedExpression) expression = ((ParenthesizedExpressionSyntax)expression).Expression; var memberModel = GetMemberModel(expression); if (memberModel == null) { // Recover from error cases var node = new BoundBadStatement(expression, ImmutableArray<BoundNode>.Empty, hasErrors: true); return new RegionAnalysisContext(Compilation, null, node, node, node); } Symbol member; BoundNode boundNode = GetBoundRoot(memberModel, out member); var first = memberModel.GetUpperBoundNode(expression, promoteToBindable: true); var last = first; return new RegionAnalysisContext(this.Compilation, member, boundNode, first, last); } private RegionAnalysisContext RegionAnalysisContext(StatementSyntax firstStatement, StatementSyntax lastStatement) { var memberModel = GetMemberModel(firstStatement); if (memberModel == null) { // Recover from error cases var node = new BoundBadStatement(firstStatement, ImmutableArray<BoundNode>.Empty, hasErrors: true); return new RegionAnalysisContext(Compilation, null, node, node, node); } Symbol member; BoundNode boundNode = GetBoundRoot(memberModel, out member); var first = memberModel.GetUpperBoundNode(firstStatement, promoteToBindable: true); var last = memberModel.GetUpperBoundNode(lastStatement, promoteToBindable: true); return new RegionAnalysisContext(Compilation, member, boundNode, first, last); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.LanguageServices; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpSyntaxFactsServiceTests { private static bool IsQueryKeyword(string markup) { MarkupTestFile.GetPosition(markup, out var code, out int position); var tree = SyntaxFactory.ParseSyntaxTree(code); var token = tree.GetRoot().FindToken(position); var service = CSharpSyntaxFacts.Instance; return service.IsQueryKeyword(token); } private static string WrapInMethod(string methodBody) { return $@" class C {{ void M() {{ {methodBody} }} }}"; } [Fact] public void IsQueryKeyword_From() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = $$from var1 in collection1"))); } [Fact] public void IsQueryKeyword_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = from var1 $$in collection1"))); } [Fact] public void IsQueryKeyword_Where() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers $$where cust.CustomerID = 1"))); } [Fact] public void IsQueryKeyword_Select() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers from ord in orders where cust.CustomerID == ord.CustomerID $$select cust.CompanyName, ord.OrderDate"))); } [Fact] public void IsQueryKeyword_GroupBy_Group() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers $$group cust by cust.Country into g"))); } [Fact] public void IsQueryKeyword_GroupBy_By() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust $$by cust.Country into g"))); } [Fact] public void IsQueryKeyword_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust by cust.Country $$into g"))); } [Fact] public void IsQueryKeyword_GroupJoin_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person equals pet.Owner $$into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_Join_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Let() { Assert.True(IsQueryKeyword(WrapInMethod(@" var discountedProducts = from prod in products $$let discount = prod.UnitPrice * 0.1 where discount >= 50 select new { prod.ProductName, prod.UnitPrice, Discount }"))); } [Fact] public void IsQueryKeyword_OrderBy_OrderBy() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books $$orderby book.Price descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Descending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price $$descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Ascending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price descending, book.Title $$ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_Not_ForEach_In() { Assert.False(IsQueryKeyword(WrapInMethod(@" foreach (var i $$in new int[0]) { }"))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpSyntaxFactsServiceTests { private static bool IsQueryKeyword(string markup) { MarkupTestFile.GetPosition(markup, out var code, out int position); var tree = SyntaxFactory.ParseSyntaxTree(code); var token = tree.GetRoot().FindToken(position); var service = CSharpSyntaxFacts.Instance; return service.IsQueryKeyword(token); } private static string WrapInMethod(string methodBody) { return $@" class C {{ void M() {{ {methodBody} }} }}"; } [Fact] public void IsQueryKeyword_From() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = $$from var1 in collection1"))); } [Fact] public void IsQueryKeyword_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = from var1 $$in collection1"))); } [Fact] public void IsQueryKeyword_Where() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers $$where cust.CustomerID = 1"))); } [Fact] public void IsQueryKeyword_Select() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers from ord in orders where cust.CustomerID == ord.CustomerID $$select cust.CompanyName, ord.OrderDate"))); } [Fact] public void IsQueryKeyword_GroupBy_Group() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers $$group cust by cust.Country into g"))); } [Fact] public void IsQueryKeyword_GroupBy_By() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust $$by cust.Country into g"))); } [Fact] public void IsQueryKeyword_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust by cust.Country $$into g"))); } [Fact] public void IsQueryKeyword_GroupJoin_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person equals pet.Owner $$into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_Join_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Let() { Assert.True(IsQueryKeyword(WrapInMethod(@" var discountedProducts = from prod in products $$let discount = prod.UnitPrice * 0.1 where discount >= 50 select new { prod.ProductName, prod.UnitPrice, Discount }"))); } [Fact] public void IsQueryKeyword_OrderBy_OrderBy() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books $$orderby book.Price descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Descending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price $$descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Ascending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price descending, book.Title $$ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_Not_ForEach_In() { Assert.False(IsQueryKeyword(WrapInMethod(@" foreach (var i $$in new int[0]) { }"))); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core.Cocoa/Structure/StructureTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure { [Export(typeof(ITaggerProvider))] [TagType(typeof(IStructureTag))] [ContentType(ContentTypeNames.RoslynContentType)] internal partial class StructureTaggerProvider : AbstractStructureTaggerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StructureTaggerProvider( IThreadingContext threadingContext, IEditorOptionsFactoryService editorOptionsFactoryService, IProjectionBufferFactoryService projectionBufferFactoryService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, editorOptionsFactoryService, projectionBufferFactoryService, listenerProvider) { } internal override object? GetCollapsedHintForm(StructureTag structureTag) { return CreateElisionBufferForTagTooltip(structureTag).CurrentSnapshot.GetText(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure { [Export(typeof(ITaggerProvider))] [TagType(typeof(IStructureTag))] [ContentType(ContentTypeNames.RoslynContentType)] internal partial class StructureTaggerProvider : AbstractStructureTaggerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StructureTaggerProvider( IThreadingContext threadingContext, IEditorOptionsFactoryService editorOptionsFactoryService, IProjectionBufferFactoryService projectionBufferFactoryService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, editorOptionsFactoryService, projectionBufferFactoryService, listenerProvider) { } internal override object? GetCollapsedHintForm(StructureTag structureTag) { return CreateElisionBufferForTagTooltip(structureTag).CurrentSnapshot.GetText(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests { [Fact] public void DiagnosticAnalyzerAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers/attributes. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); // Add nodes that are not yet in AllInOneCSharpCode to this list. var missingSyntaxKinds = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 Add to all in one missingSyntaxKinds.Add(SyntaxKind.WithExpression); missingSyntaxKinds.Add(SyntaxKind.RecordDeclaration); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxKinds); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks); } [WorkItem(896075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896075")] [Fact] public void DiagnosticAnalyzerIndexerDeclaration() { var source = @" public class C { public string this[int index] { get { return string.Empty; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } // AllInOne does not include experimental features. #region Experimental Features [Fact] public void DiagnosticAnalyzerConditionalAccess() { var source = @" public class C { public string this[int index] { get { return string.Empty ?. ToString() ?[1] .ToString() ; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } [Fact] public void DiagnosticAnalyzerExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" public class C { public int P => 10; }").VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } #endregion [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public void AnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptions(analyzer => compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options)); } [Fact] public void AnalyzerOptionsArePassedToAllAnalyzers() { var text = new StringText(string.Empty, encodingOpt: null); AnalyzerOptions options = new AnalyzerOptions ( new[] { new TestAdditionalText("myfilepath", text) }.ToImmutableArray<AdditionalText>() ); var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(options); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAnalyzerOptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests { [Fact] public void DiagnosticAnalyzerAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers/attributes. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); // Add nodes that are not yet in AllInOneCSharpCode to this list. var missingSyntaxKinds = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 Add to all in one missingSyntaxKinds.Add(SyntaxKind.WithExpression); missingSyntaxKinds.Add(SyntaxKind.RecordDeclaration); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxKinds); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks); } [WorkItem(896075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896075")] [Fact] public void DiagnosticAnalyzerIndexerDeclaration() { var source = @" public class C { public string this[int index] { get { return string.Empty; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } // AllInOne does not include experimental features. #region Experimental Features [Fact] public void DiagnosticAnalyzerConditionalAccess() { var source = @" public class C { public string this[int index] { get { return string.Empty ?. ToString() ?[1] .ToString() ; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } [Fact] public void DiagnosticAnalyzerExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" public class C { public int P => 10; }").VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } #endregion [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public void AnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptions(analyzer => compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options)); } [Fact] public void AnalyzerOptionsArePassedToAllAnalyzers() { var text = new StringText(string.Empty, encodingOpt: null); AnalyzerOptions options = new AnalyzerOptions ( new[] { new TestAdditionalText("myfilepath", text) }.ToImmutableArray<AdditionalText>() ); var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(options); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAnalyzerOptions(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/CSharp/Impl/EditorConfigSettings/BinaryOperatorSpacingOptionsViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { internal class BinaryOperatorSpacingOptionsViewModel : EnumSettingViewModel<BinaryOperatorSpacingOptions> { private readonly WhitespaceSetting _setting; public BinaryOperatorSpacingOptionsViewModel(WhitespaceSetting setting) { _setting = setting; } protected override void ChangePropertyTo(BinaryOperatorSpacingOptions newValue) { _setting.SetValue(newValue); } protected override BinaryOperatorSpacingOptions GetCurrentValue() { return (BinaryOperatorSpacingOptions)_setting.GetValue()!; } protected override IReadOnlyDictionary<string, BinaryOperatorSpacingOptions> GetValuesAndDescriptions() { return EnumerateOptions().ToDictionary(x => x.description, x => x.value); static IEnumerable<(string description, BinaryOperatorSpacingOptions value)> EnumerateOptions() { yield return (CSharpVSResources.Ignore_spaces_around_binary_operators, BinaryOperatorSpacingOptions.Ignore); yield return (CSharpVSResources.Remove_spaces_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Remove); yield return (CSharpVSResources.Insert_space_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Single); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { internal class BinaryOperatorSpacingOptionsViewModel : EnumSettingViewModel<BinaryOperatorSpacingOptions> { private readonly WhitespaceSetting _setting; public BinaryOperatorSpacingOptionsViewModel(WhitespaceSetting setting) { _setting = setting; } protected override void ChangePropertyTo(BinaryOperatorSpacingOptions newValue) { _setting.SetValue(newValue); } protected override BinaryOperatorSpacingOptions GetCurrentValue() { return (BinaryOperatorSpacingOptions)_setting.GetValue()!; } protected override IReadOnlyDictionary<string, BinaryOperatorSpacingOptions> GetValuesAndDescriptions() { return EnumerateOptions().ToDictionary(x => x.description, x => x.value); static IEnumerable<(string description, BinaryOperatorSpacingOptions value)> EnumerateOptions() { yield return (CSharpVSResources.Ignore_spaces_around_binary_operators, BinaryOperatorSpacingOptions.Ignore); yield return (CSharpVSResources.Remove_spaces_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Remove); yield return (CSharpVSResources.Insert_space_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Single); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/PatternMatching/PatternMatchKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PatternMatching { /// <summary> /// Note(cyrusn): this enum is ordered from strongest match type to weakest match type. /// </summary> internal enum PatternMatchKind { /// <summary> /// The candidate string matched the pattern exactly. /// </summary> Exact, /// <summary> /// The pattern was a prefix of the candidate string. /// </summary> Prefix, /// <summary> /// The pattern was a substring of the candidate string, but in a way that wasn't a CamelCase match. The /// pattern had to have at least one non lowercase letter in it, and the match needs to be case sensitive. /// This will match 'savedWork' against 'FindUnsavedWork'. /// </summary> NonLowercaseSubstring, /// <summary> /// The pattern was a substring of the candidate string, starting at a word within that candidate. The pattern /// can be all lowercase here. This will match 'save' or 'Save' in 'FindSavedWork' /// </summary> StartOfWordSubstring, // Note: CamelCased matches are ordered from best to worst. /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. All camel-humps /// in the candidate were matched by a camel-hump in the pattern. /// /// Example: "CFPS" matching "CodeFixProviderService" /// Example: "cfps" matching "CodeFixProviderService" /// Example: "CoFiPrSe" matching "CodeFixProviderService" /// </summary> CamelCaseExact, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern matched the first camel-hump in the candidate. There was no gap in the camel- /// humps in the candidate that were matched. /// /// Example: "CFP" matching "CodeFixProviderService" /// Example: "cfp" matching "CodeFixProviderService" /// Example: "CoFiPRo" matching "CodeFixProviderService" /// </summary> CamelCasePrefix, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern matched the first camel-hump in the candidate. There was at least one gap in /// the camel-humps in the candidate that were matched. /// /// Example: "CP" matching "CodeFixProviderService" /// Example: "cp" matching "CodeFixProviderService" /// Example: "CoProv" matching "CodeFixProviderService" /// </summary> CamelCaseNonContiguousPrefix, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern did not match the first camel-hump in the pattern. There was no gap in the camel- /// humps in the candidate that were matched. /// /// Example: "FP" matching "CodeFixProviderService" /// Example: "fp" matching "CodeFixProviderService" /// Example: "FixPro" matching "CodeFixProviderService" /// </summary> CamelCaseSubstring, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern did not match the first camel-hump in the pattern. There was at least one gap in /// the camel-humps in the candidate that were matched. /// /// Example: "FS" matching "CodeFixProviderService" /// Example: "fs" matching "CodeFixProviderService" /// Example: "FixSer" matching "CodeFixProviderService" /// </summary> CamelCaseNonContiguousSubstring, /// <summary> /// The pattern matches the candidate in a fuzzy manner. Fuzzy matching allows for /// a certain amount of misspellings, missing words, etc. See <see cref="SpellChecker"/> for /// more details. /// </summary> Fuzzy, /// <summary> /// The pattern was a substring of the candidate and wasn't either <see cref="NonLowercaseSubstring"/> or <see /// cref="StartOfWordSubstring"/>. This can happen when the pattern is allow lowercases and matches some non /// word portion of the candidate. For example, finding 'save' in 'GetUnsavedWork'. This will not match across /// word boundaries. i.e. it will not match 'save' to 'VisaVerify' even though 'saVe' is in that candidate. /// </summary> LowercaseSubstring, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PatternMatching { /// <summary> /// Note(cyrusn): this enum is ordered from strongest match type to weakest match type. /// </summary> internal enum PatternMatchKind { /// <summary> /// The candidate string matched the pattern exactly. /// </summary> Exact, /// <summary> /// The pattern was a prefix of the candidate string. /// </summary> Prefix, /// <summary> /// The pattern was a substring of the candidate string, but in a way that wasn't a CamelCase match. The /// pattern had to have at least one non lowercase letter in it, and the match needs to be case sensitive. /// This will match 'savedWork' against 'FindUnsavedWork'. /// </summary> NonLowercaseSubstring, /// <summary> /// The pattern was a substring of the candidate string, starting at a word within that candidate. The pattern /// can be all lowercase here. This will match 'save' or 'Save' in 'FindSavedWork' /// </summary> StartOfWordSubstring, // Note: CamelCased matches are ordered from best to worst. /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. All camel-humps /// in the candidate were matched by a camel-hump in the pattern. /// /// Example: "CFPS" matching "CodeFixProviderService" /// Example: "cfps" matching "CodeFixProviderService" /// Example: "CoFiPrSe" matching "CodeFixProviderService" /// </summary> CamelCaseExact, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern matched the first camel-hump in the candidate. There was no gap in the camel- /// humps in the candidate that were matched. /// /// Example: "CFP" matching "CodeFixProviderService" /// Example: "cfp" matching "CodeFixProviderService" /// Example: "CoFiPRo" matching "CodeFixProviderService" /// </summary> CamelCasePrefix, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern matched the first camel-hump in the candidate. There was at least one gap in /// the camel-humps in the candidate that were matched. /// /// Example: "CP" matching "CodeFixProviderService" /// Example: "cp" matching "CodeFixProviderService" /// Example: "CoProv" matching "CodeFixProviderService" /// </summary> CamelCaseNonContiguousPrefix, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern did not match the first camel-hump in the pattern. There was no gap in the camel- /// humps in the candidate that were matched. /// /// Example: "FP" matching "CodeFixProviderService" /// Example: "fp" matching "CodeFixProviderService" /// Example: "FixPro" matching "CodeFixProviderService" /// </summary> CamelCaseSubstring, /// <summary> /// All camel-humps in the pattern matched a camel-hump in the candidate. The first camel-hump /// in the pattern did not match the first camel-hump in the pattern. There was at least one gap in /// the camel-humps in the candidate that were matched. /// /// Example: "FS" matching "CodeFixProviderService" /// Example: "fs" matching "CodeFixProviderService" /// Example: "FixSer" matching "CodeFixProviderService" /// </summary> CamelCaseNonContiguousSubstring, /// <summary> /// The pattern matches the candidate in a fuzzy manner. Fuzzy matching allows for /// a certain amount of misspellings, missing words, etc. See <see cref="SpellChecker"/> for /// more details. /// </summary> Fuzzy, /// <summary> /// The pattern was a substring of the candidate and wasn't either <see cref="NonLowercaseSubstring"/> or <see /// cref="StartOfWordSubstring"/>. This can happen when the pattern is allow lowercases and matches some non /// word portion of the candidate. For example, finding 'save' in 'GetUnsavedWork'. This will not match across /// word boundaries. i.e. it will not match 'save' to 'VisaVerify' even though 'saVe' is in that candidate. /// </summary> LowercaseSubstring, } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferenceCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { // TODO : this can be all moved down to compiler side. internal static class FindReferenceCache { private static readonly ReaderWriterLockSlim s_gate = new(); private static readonly Dictionary<SemanticModel, Entry> s_cache = new(); public static SymbolInfo GetSymbolInfo(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { var nodeCache = GetNodeCache(model); if (nodeCache == null) { return model.GetSymbolInfo(node, cancellationToken); } return nodeCache.GetOrAdd(node, static (n, arg) => arg.model.GetSymbolInfo(n, arg.cancellationToken), (model, cancellationToken)); } public static IAliasSymbol GetAliasInfo( ISemanticFactsService semanticFacts, SemanticModel model, SyntaxToken token, CancellationToken cancellationToken) { if (semanticFacts == null) { return model.GetAliasInfo(token.Parent, cancellationToken); } var entry = GetCachedEntry(model); if (entry == null) { return model.GetAliasInfo(token.Parent, cancellationToken); } if (entry.AliasNameSet == null) { var set = semanticFacts.GetAliasNameSet(model, cancellationToken); Interlocked.CompareExchange(ref entry.AliasNameSet, set, null); } if (entry.AliasNameSet.Contains(token.ValueText)) { return model.GetAliasInfo(token.Parent, cancellationToken); } return null; } public static ImmutableArray<SyntaxToken> GetIdentifierOrGlobalNamespaceTokensWithText( ISyntaxFactsService syntaxFacts, SemanticModel model, SyntaxNode root, SourceText sourceText, string text, CancellationToken cancellationToken) { var normalized = syntaxFacts.IsCaseSensitive ? text : text.ToLowerInvariant(); var entry = GetCachedEntry(model); if (entry == null) { return GetIdentifierOrGlobalNamespaceTokensWithText(syntaxFacts, root, sourceText, normalized, cancellationToken); } return entry.IdentifierCache.GetOrAdd(normalized, key => GetIdentifierOrGlobalNamespaceTokensWithText( syntaxFacts, root, sourceText, key, cancellationToken)); } [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", AllowCaptures = false)] private static ImmutableArray<SyntaxToken> GetIdentifierOrGlobalNamespaceTokensWithText( ISyntaxFactsService syntaxFacts, SyntaxNode root, SourceText sourceText, string text, CancellationToken cancellationToken) { if (sourceText != null) { // identifier is not escaped Func<SyntaxToken, ISyntaxFactsService, string, bool> isCandidate = static (t, syntaxFacts, text) => IsCandidate(t, syntaxFacts, text); return GetTokensFromText(syntaxFacts, root, sourceText, text, isCandidate, cancellationToken); } else { // identifier is escaped using var _ = PooledDelegates.GetPooledFunction<SyntaxToken, (ISyntaxFactsService syntaxFacts, string text), bool>( static (t, arg) => IsCandidate(t, arg.syntaxFacts, arg.text), (syntaxFacts, text), out var isCandidate); return root.DescendantTokens(descendIntoTrivia: true).Where(isCandidate).ToImmutableArray(); } static bool IsCandidate(SyntaxToken t, ISyntaxFactsService syntaxFacts, string text) => syntaxFacts.IsGlobalNamespaceKeyword(t) || (syntaxFacts.IsIdentifier(t) && syntaxFacts.TextMatch(t.ValueText, text)); } private static ImmutableArray<SyntaxToken> GetTokensFromText( ISyntaxFactsService syntaxFacts, SyntaxNode root, SourceText content, string text, Func<SyntaxToken, ISyntaxFactsService, string, bool> candidate, CancellationToken cancellationToken) { if (text.Length == 0) { return ImmutableArray<SyntaxToken>.Empty; } var result = ImmutableArray.CreateBuilder<SyntaxToken>(); var index = 0; while ((index = content.IndexOf(text, index, syntaxFacts.IsCaseSensitive)) >= 0) { cancellationToken.ThrowIfCancellationRequested(); var nextIndex = index + text.Length; var token = root.FindToken(index, findInsideTrivia: true); var span = token.Span; if (!token.IsMissing && span.Start == index && span.Length == text.Length && candidate(token, syntaxFacts, text)) { result.Add(token); } nextIndex = Math.Max(nextIndex, token.SpanStart); index = nextIndex; } return result.ToImmutable(); } public static IEnumerable<SyntaxToken> GetConstructorInitializerTokens( ISyntaxFactsService syntaxFacts, SemanticModel model, SyntaxNode root, CancellationToken cancellationToken) { // this one will only get called when we know given document contains constructor initializer. // no reason to use text to check whether it exist first. var entry = GetCachedEntry(model); if (entry == null) { return GetConstructorInitializerTokens(syntaxFacts, root, cancellationToken); } if (entry.ConstructorInitializerCache == null) { var initializers = GetConstructorInitializerTokens(syntaxFacts, root, cancellationToken); Interlocked.CompareExchange(ref entry.ConstructorInitializerCache, initializers, null); } return entry.ConstructorInitializerCache; } private static List<SyntaxToken> GetConstructorInitializerTokens( ISyntaxFactsService syntaxFacts, SyntaxNode root, CancellationToken cancellationToken) { var initializers = new List<SyntaxToken>(); foreach (var constructor in syntaxFacts.GetConstructors(root, cancellationToken)) { foreach (var token in constructor.DescendantTokens(descendIntoTrivia: false)) { if (!syntaxFacts.IsThisConstructorInitializer(token) && !syntaxFacts.IsBaseConstructorInitializer(token)) { continue; } initializers.Add(token); } } return initializers; } private static ConcurrentDictionary<SyntaxNode, SymbolInfo> GetNodeCache(SemanticModel model) { var entry = GetCachedEntry(model); if (entry == null) { return null; } return entry.SymbolInfoCache; } private static Entry GetCachedEntry(SemanticModel model) { using (s_gate.DisposableRead()) { if (s_cache.TryGetValue(model, out var entry)) { return entry; } return null; } } private static readonly Func<SemanticModel, Entry> s_entryCreator = _ => new Entry(); public static void Start(SemanticModel model) { Debug.Assert(model != null); using (s_gate.DisposableWrite()) { var entry = s_cache.GetOrAdd(model, s_entryCreator); entry.Count++; } } public static void Stop(SemanticModel model) { if (model == null) { return; } using (s_gate.DisposableWrite()) { if (!s_cache.TryGetValue(model, out var entry)) { return; } entry.Count--; if (entry.Count == 0) { s_cache.Remove(model); } } } private class Entry { public int Count; public ImmutableHashSet<string> AliasNameSet; public List<SyntaxToken> ConstructorInitializerCache; public readonly ConcurrentDictionary<string, ImmutableArray<SyntaxToken>> IdentifierCache = new(); public readonly ConcurrentDictionary<SyntaxNode, SymbolInfo> SymbolInfoCache = new(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { // TODO : this can be all moved down to compiler side. internal static class FindReferenceCache { private static readonly ReaderWriterLockSlim s_gate = new(); private static readonly Dictionary<SemanticModel, Entry> s_cache = new(); public static SymbolInfo GetSymbolInfo(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { var nodeCache = GetNodeCache(model); if (nodeCache == null) { return model.GetSymbolInfo(node, cancellationToken); } return nodeCache.GetOrAdd(node, static (n, arg) => arg.model.GetSymbolInfo(n, arg.cancellationToken), (model, cancellationToken)); } public static IAliasSymbol GetAliasInfo( ISemanticFactsService semanticFacts, SemanticModel model, SyntaxToken token, CancellationToken cancellationToken) { if (semanticFacts == null) { return model.GetAliasInfo(token.Parent, cancellationToken); } var entry = GetCachedEntry(model); if (entry == null) { return model.GetAliasInfo(token.Parent, cancellationToken); } if (entry.AliasNameSet == null) { var set = semanticFacts.GetAliasNameSet(model, cancellationToken); Interlocked.CompareExchange(ref entry.AliasNameSet, set, null); } if (entry.AliasNameSet.Contains(token.ValueText)) { return model.GetAliasInfo(token.Parent, cancellationToken); } return null; } public static ImmutableArray<SyntaxToken> GetIdentifierOrGlobalNamespaceTokensWithText( ISyntaxFactsService syntaxFacts, SemanticModel model, SyntaxNode root, SourceText sourceText, string text, CancellationToken cancellationToken) { var normalized = syntaxFacts.IsCaseSensitive ? text : text.ToLowerInvariant(); var entry = GetCachedEntry(model); if (entry == null) { return GetIdentifierOrGlobalNamespaceTokensWithText(syntaxFacts, root, sourceText, normalized, cancellationToken); } return entry.IdentifierCache.GetOrAdd(normalized, key => GetIdentifierOrGlobalNamespaceTokensWithText( syntaxFacts, root, sourceText, key, cancellationToken)); } [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", AllowCaptures = false)] private static ImmutableArray<SyntaxToken> GetIdentifierOrGlobalNamespaceTokensWithText( ISyntaxFactsService syntaxFacts, SyntaxNode root, SourceText sourceText, string text, CancellationToken cancellationToken) { if (sourceText != null) { // identifier is not escaped Func<SyntaxToken, ISyntaxFactsService, string, bool> isCandidate = static (t, syntaxFacts, text) => IsCandidate(t, syntaxFacts, text); return GetTokensFromText(syntaxFacts, root, sourceText, text, isCandidate, cancellationToken); } else { // identifier is escaped using var _ = PooledDelegates.GetPooledFunction<SyntaxToken, (ISyntaxFactsService syntaxFacts, string text), bool>( static (t, arg) => IsCandidate(t, arg.syntaxFacts, arg.text), (syntaxFacts, text), out var isCandidate); return root.DescendantTokens(descendIntoTrivia: true).Where(isCandidate).ToImmutableArray(); } static bool IsCandidate(SyntaxToken t, ISyntaxFactsService syntaxFacts, string text) => syntaxFacts.IsGlobalNamespaceKeyword(t) || (syntaxFacts.IsIdentifier(t) && syntaxFacts.TextMatch(t.ValueText, text)); } private static ImmutableArray<SyntaxToken> GetTokensFromText( ISyntaxFactsService syntaxFacts, SyntaxNode root, SourceText content, string text, Func<SyntaxToken, ISyntaxFactsService, string, bool> candidate, CancellationToken cancellationToken) { if (text.Length == 0) { return ImmutableArray<SyntaxToken>.Empty; } var result = ImmutableArray.CreateBuilder<SyntaxToken>(); var index = 0; while ((index = content.IndexOf(text, index, syntaxFacts.IsCaseSensitive)) >= 0) { cancellationToken.ThrowIfCancellationRequested(); var nextIndex = index + text.Length; var token = root.FindToken(index, findInsideTrivia: true); var span = token.Span; if (!token.IsMissing && span.Start == index && span.Length == text.Length && candidate(token, syntaxFacts, text)) { result.Add(token); } nextIndex = Math.Max(nextIndex, token.SpanStart); index = nextIndex; } return result.ToImmutable(); } public static IEnumerable<SyntaxToken> GetConstructorInitializerTokens( ISyntaxFactsService syntaxFacts, SemanticModel model, SyntaxNode root, CancellationToken cancellationToken) { // this one will only get called when we know given document contains constructor initializer. // no reason to use text to check whether it exist first. var entry = GetCachedEntry(model); if (entry == null) { return GetConstructorInitializerTokens(syntaxFacts, root, cancellationToken); } if (entry.ConstructorInitializerCache == null) { var initializers = GetConstructorInitializerTokens(syntaxFacts, root, cancellationToken); Interlocked.CompareExchange(ref entry.ConstructorInitializerCache, initializers, null); } return entry.ConstructorInitializerCache; } private static List<SyntaxToken> GetConstructorInitializerTokens( ISyntaxFactsService syntaxFacts, SyntaxNode root, CancellationToken cancellationToken) { var initializers = new List<SyntaxToken>(); foreach (var constructor in syntaxFacts.GetConstructors(root, cancellationToken)) { foreach (var token in constructor.DescendantTokens(descendIntoTrivia: false)) { if (!syntaxFacts.IsThisConstructorInitializer(token) && !syntaxFacts.IsBaseConstructorInitializer(token)) { continue; } initializers.Add(token); } } return initializers; } private static ConcurrentDictionary<SyntaxNode, SymbolInfo> GetNodeCache(SemanticModel model) { var entry = GetCachedEntry(model); if (entry == null) { return null; } return entry.SymbolInfoCache; } private static Entry GetCachedEntry(SemanticModel model) { using (s_gate.DisposableRead()) { if (s_cache.TryGetValue(model, out var entry)) { return entry; } return null; } } private static readonly Func<SemanticModel, Entry> s_entryCreator = _ => new Entry(); public static void Start(SemanticModel model) { Debug.Assert(model != null); using (s_gate.DisposableWrite()) { var entry = s_cache.GetOrAdd(model, s_entryCreator); entry.Count++; } } public static void Stop(SemanticModel model) { if (model == null) { return; } using (s_gate.DisposableWrite()) { if (!s_cache.TryGetValue(model, out var entry)) { return; } entry.Count--; if (entry.Count == 0) { s_cache.Remove(model); } } } private class Entry { public int Count; public ImmutableHashSet<string> AliasNameSet; public List<SyntaxToken> ConstructorInitializerCache; public readonly ConcurrentDictionary<string, ImmutableArray<SyntaxToken>> IdentifierCache = new(); public readonly ConcurrentDictionary<SyntaxNode, SymbolInfo> SymbolInfoCache = new(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Action that will sync the namespace of the document to match the folders property /// of that document, similar to if a user performed the "Sync Namespace" code refactoring. /// /// For example, if a document is moved from "Bat/Bar/Baz" folder structure to "Bat/Bar/Baz/Bat" and contains /// a namespace definition of Bat.Bar.Baz in the document, then it would update that definition to /// Bat.Bar.Baz.Bat and update the solution to reflect these changes. Uses <see cref="IChangeNamespaceService"/> /// </summary> internal sealed class SyncNamespaceDocumentAction : RenameDocumentAction { private readonly AnalysisResult _analysis; private SyncNamespaceDocumentAction(AnalysisResult analysis) : base(ImmutableArray<ErrorResource>.Empty) { _analysis = analysis; } public override string GetDescription(CultureInfo? culture) => WorkspacesResources.ResourceManager.GetString("Sync_namespace_to_folder_structure", culture ?? WorkspacesResources.Culture)!; internal override async Task<Solution> GetModifiedSolutionAsync(Document document, OptionSet _, CancellationToken cancellationToken) { var changeNamespaceService = document.GetRequiredLanguageService<IChangeNamespaceService>(); var solution = await changeNamespaceService.TryChangeTopLevelNamespacesAsync(document, _analysis.TargetNamespace, cancellationToken).ConfigureAwait(false); // If the solution fails to update fail silently. The user will see no large // negative impact from not doing this modification, and it's possible the document // was too malformed to update any namespaces. return solution ?? document.Project.Solution; } public static SyncNamespaceDocumentAction? TryCreate(Document document, IReadOnlyList<string> newFolders, CancellationToken _) { var analysisResult = Analyze(document, newFolders); if (analysisResult.HasValue) { return new SyncNamespaceDocumentAction(analysisResult.Value); } return null; } private static AnalysisResult? Analyze(Document document, IReadOnlyCollection<string> newFolders) { // https://github.com/dotnet/roslyn/issues/41841 // VB implementation is incomplete for sync namespace if (document.Project.Language == LanguageNames.CSharp) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var targetNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(newFolders, syntaxFacts, document.Project.DefaultNamespace); if (targetNamespace is null) { return null; } return new AnalysisResult(targetNamespace); } else { return null; } } private readonly struct AnalysisResult { public string TargetNamespace { get; } public AnalysisResult(string targetNamespace) { TargetNamespace = targetNamespace; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Action that will sync the namespace of the document to match the folders property /// of that document, similar to if a user performed the "Sync Namespace" code refactoring. /// /// For example, if a document is moved from "Bat/Bar/Baz" folder structure to "Bat/Bar/Baz/Bat" and contains /// a namespace definition of Bat.Bar.Baz in the document, then it would update that definition to /// Bat.Bar.Baz.Bat and update the solution to reflect these changes. Uses <see cref="IChangeNamespaceService"/> /// </summary> internal sealed class SyncNamespaceDocumentAction : RenameDocumentAction { private readonly AnalysisResult _analysis; private SyncNamespaceDocumentAction(AnalysisResult analysis) : base(ImmutableArray<ErrorResource>.Empty) { _analysis = analysis; } public override string GetDescription(CultureInfo? culture) => WorkspacesResources.ResourceManager.GetString("Sync_namespace_to_folder_structure", culture ?? WorkspacesResources.Culture)!; internal override async Task<Solution> GetModifiedSolutionAsync(Document document, OptionSet _, CancellationToken cancellationToken) { var changeNamespaceService = document.GetRequiredLanguageService<IChangeNamespaceService>(); var solution = await changeNamespaceService.TryChangeTopLevelNamespacesAsync(document, _analysis.TargetNamespace, cancellationToken).ConfigureAwait(false); // If the solution fails to update fail silently. The user will see no large // negative impact from not doing this modification, and it's possible the document // was too malformed to update any namespaces. return solution ?? document.Project.Solution; } public static SyncNamespaceDocumentAction? TryCreate(Document document, IReadOnlyList<string> newFolders, CancellationToken _) { var analysisResult = Analyze(document, newFolders); if (analysisResult.HasValue) { return new SyncNamespaceDocumentAction(analysisResult.Value); } return null; } private static AnalysisResult? Analyze(Document document, IReadOnlyCollection<string> newFolders) { // https://github.com/dotnet/roslyn/issues/41841 // VB implementation is incomplete for sync namespace if (document.Project.Language == LanguageNames.CSharp) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var targetNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(newFolders, syntaxFacts, document.Project.DefaultNamespace); if (targetNamespace is null) { return null; } return new AnalysisResult(targetNamespace); } else { return null; } } private readonly struct AnalysisResult { public string TargetNamespace { get; } public AnalysisResult(string targetNamespace) { TargetNamespace = targetNamespace; } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Dependencies/Collections/ImmutableSegmentedDictionary`2+Builder+ValueCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public partial class Builder { public readonly struct ValueCollection : ICollection<TValue>, IReadOnlyCollection<TValue>, ICollection { private readonly ImmutableSegmentedDictionary<TKey, TValue>.Builder _dictionary; internal ValueCollection(ImmutableSegmentedDictionary<TKey, TValue>.Builder dictionary) { Debug.Assert(dictionary is not null); _dictionary = dictionary!; } public int Count => _dictionary.Count; bool ICollection<TValue>.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; void ICollection<TValue>.Add(TValue item) => throw new NotSupportedException(); public void Clear() => _dictionary.Clear(); public bool Contains(TValue item) => _dictionary.ContainsValue(item); public void CopyTo(TValue[] array, int arrayIndex) => ((ICollection<TValue>)_dictionary.ReadOnlyDictionary.Values).CopyTo(array, arrayIndex); public ImmutableSegmentedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() => new(_dictionary.GetEnumerator()); bool ICollection<TValue>.Remove(TValue item) => throw new NotSupportedException(); void ICollection.CopyTo(Array array, int index) => ((ICollection)_dictionary.ReadOnlyDictionary.Values).CopyTo(array, index); IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public partial class Builder { public readonly struct ValueCollection : ICollection<TValue>, IReadOnlyCollection<TValue>, ICollection { private readonly ImmutableSegmentedDictionary<TKey, TValue>.Builder _dictionary; internal ValueCollection(ImmutableSegmentedDictionary<TKey, TValue>.Builder dictionary) { Debug.Assert(dictionary is not null); _dictionary = dictionary!; } public int Count => _dictionary.Count; bool ICollection<TValue>.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; void ICollection<TValue>.Add(TValue item) => throw new NotSupportedException(); public void Clear() => _dictionary.Clear(); public bool Contains(TValue item) => _dictionary.ContainsValue(item); public void CopyTo(TValue[] array, int arrayIndex) => ((ICollection<TValue>)_dictionary.ReadOnlyDictionary.Values).CopyTo(array, arrayIndex); public ImmutableSegmentedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() => new(_dictionary.GetEnumerator()); bool ICollection<TValue>.Remove(TValue item) => throw new NotSupportedException(); void ICollection.CopyTo(Array array, int index) => ((ICollection)_dictionary.ReadOnlyDictionary.Values).CopyTo(array, index); IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicErrorListDesktop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicErrorListDesktop : BasicErrorListCommon { public BasicErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicErrorListDesktop : BasicErrorListCommon { public BasicErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ValuesSources/ConstantValueSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { /// <summary> /// This value source keeps a strong reference to a value. /// </summary> internal sealed class ConstantValueSource<T> : ValueSource<T> { private readonly T _value; private Task<T>? _task; public ConstantValueSource(T value) => _value = value; public override T GetValue(CancellationToken cancellationToken = default) => _value; public override bool TryGetValue([MaybeNullWhen(false)] out T value) { value = _value; return true; } public override Task<T> GetValueAsync(CancellationToken cancellationToken = default) { if (_task == null) { Interlocked.CompareExchange(ref _task, Task.FromResult(_value), null); } return _task; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { /// <summary> /// This value source keeps a strong reference to a value. /// </summary> internal sealed class ConstantValueSource<T> : ValueSource<T> { private readonly T _value; private Task<T>? _task; public ConstantValueSource(T value) => _value = value; public override T GetValue(CancellationToken cancellationToken = default) => _value; public override bool TryGetValue([MaybeNullWhen(false)] out T value) { value = _value; return true; } public override Task<T> GetValueAsync(CancellationToken cancellationToken = default) { if (_task == null) { Interlocked.CompareExchange(ref _task, Task.FromResult(_value), null); } return _task; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/SettingsProviderBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using static Microsoft.CodeAnalysis.ProjectState; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal abstract class SettingsProviderBase<TData, TOptionsUpdater, TOption, TValue> : ISettingsProvider<TData> where TOptionsUpdater : ISettingUpdater<TOption, TValue> { private readonly List<TData> _snapshot = new(); private static readonly object s_gate = new(); private ISettingsEditorViewModel? _viewModel; protected readonly string FileName; protected readonly TOptionsUpdater SettingsUpdater; protected readonly Workspace Workspace; protected abstract void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions); protected SettingsProviderBase(string fileName, TOptionsUpdater settingsUpdater, Workspace workspace) { FileName = fileName; SettingsUpdater = settingsUpdater; Workspace = workspace; } protected void Update() { var givenFolder = new DirectoryInfo(FileName).Parent; var solution = Workspace.CurrentSolution; var projects = solution.GetProjectsForPath(FileName); var project = projects.FirstOrDefault(); if (project is null) { // no .NET projects in the solution return; } var configOptionsProvider = new WorkspaceAnalyzerConfigOptionsProvider(project.State); var workspaceOptions = configOptionsProvider.GetOptionsForSourcePath(givenFolder.FullName); var result = project.GetAnalyzerConfigOptions(); var options = new CombinedAnalyzerConfigOptions(workspaceOptions, result); UpdateOptions(options, Workspace.Options); } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { if (!await SettingsUpdater.HasAnyChangesAsync().ConfigureAwait(false)) { return sourceText; } var text = await SettingsUpdater.GetChangedEditorConfigAsync(sourceText, default).ConfigureAwait(false); return text is not null ? text : sourceText; } public ImmutableArray<TData> GetCurrentDataSnapshot() { lock (s_gate) { return _snapshot.ToImmutableArray(); } } protected void AddRange(IEnumerable<TData> items) { lock (s_gate) { _snapshot.AddRange(items); } _viewModel?.NotifyOfUpdate(); } public void RegisterViewModel(ISettingsEditorViewModel viewModel) => _viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); private sealed class CombinedAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly AnalyzerConfigOptions _workspaceOptions; private readonly AnalyzerConfigOptionsResult? _result; public CombinedAnalyzerConfigOptions(AnalyzerConfigOptions workspaceOptions, AnalyzerConfigOptionsResult? result) { _workspaceOptions = workspaceOptions; _result = result; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (_workspaceOptions.TryGetValue(key, out value)) { return true; } if (!_result.HasValue) { value = null; return false; } if (_result.Value.AnalyzerOptions.TryGetValue(key, out value)) { return true; } var diagnosticKey = "dotnet_diagnostic.(?<key>.*).severity"; var match = Regex.Match(key, diagnosticKey); if (match.Success && match.Groups["key"].Value is string isolatedKey && _result.Value.TreeOptions.TryGetValue(isolatedKey, out var severity)) { value = severity.ToEditorConfigString(); return true; } value = 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using static Microsoft.CodeAnalysis.ProjectState; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal abstract class SettingsProviderBase<TData, TOptionsUpdater, TOption, TValue> : ISettingsProvider<TData> where TOptionsUpdater : ISettingUpdater<TOption, TValue> { private readonly List<TData> _snapshot = new(); private static readonly object s_gate = new(); private ISettingsEditorViewModel? _viewModel; protected readonly string FileName; protected readonly TOptionsUpdater SettingsUpdater; protected readonly Workspace Workspace; protected abstract void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions); protected SettingsProviderBase(string fileName, TOptionsUpdater settingsUpdater, Workspace workspace) { FileName = fileName; SettingsUpdater = settingsUpdater; Workspace = workspace; } protected void Update() { var givenFolder = new DirectoryInfo(FileName).Parent; var solution = Workspace.CurrentSolution; var projects = solution.GetProjectsForPath(FileName); var project = projects.FirstOrDefault(); if (project is null) { // no .NET projects in the solution return; } var configOptionsProvider = new WorkspaceAnalyzerConfigOptionsProvider(project.State); var workspaceOptions = configOptionsProvider.GetOptionsForSourcePath(givenFolder.FullName); var result = project.GetAnalyzerConfigOptions(); var options = new CombinedAnalyzerConfigOptions(workspaceOptions, result); UpdateOptions(options, Workspace.Options); } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { if (!await SettingsUpdater.HasAnyChangesAsync().ConfigureAwait(false)) { return sourceText; } var text = await SettingsUpdater.GetChangedEditorConfigAsync(sourceText, default).ConfigureAwait(false); return text is not null ? text : sourceText; } public ImmutableArray<TData> GetCurrentDataSnapshot() { lock (s_gate) { return _snapshot.ToImmutableArray(); } } protected void AddRange(IEnumerable<TData> items) { lock (s_gate) { _snapshot.AddRange(items); } _viewModel?.NotifyOfUpdate(); } public void RegisterViewModel(ISettingsEditorViewModel viewModel) => _viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); private sealed class CombinedAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly AnalyzerConfigOptions _workspaceOptions; private readonly AnalyzerConfigOptionsResult? _result; public CombinedAnalyzerConfigOptions(AnalyzerConfigOptions workspaceOptions, AnalyzerConfigOptionsResult? result) { _workspaceOptions = workspaceOptions; _result = result; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (_workspaceOptions.TryGetValue(key, out value)) { return true; } if (!_result.HasValue) { value = null; return false; } if (_result.Value.AnalyzerOptions.TryGetValue(key, out value)) { return true; } var diagnosticKey = "dotnet_diagnostic.(?<key>.*).severity"; var match = Regex.Match(key, diagnosticKey); if (match.Success && match.Groups["key"].Value is string isolatedKey && _result.Value.TreeOptions.TryGetValue(isolatedKey, out var severity)) { value = severity.ToEditorConfigString(); return true; } value = null; return false; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A source parameter, potentially with a default value, attributes, etc. /// </summary> internal class SourceComplexParameterSymbol : SourceParameterSymbol, IAttributeTargetSymbol { [Flags] private enum ParameterSyntaxKind : byte { Regular = 0, ParamsParameter = 1, ExtensionThisParameter = 2, DefaultParameter = 4, } private readonly SyntaxReference _syntaxRef; private readonly ParameterSyntaxKind _parameterSyntaxKind; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ThreeState _lazyHasOptionalAttribute; protected ConstantValue _lazyDefaultSyntaxValue; internal SourceComplexParameterSymbol( Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, string name, ImmutableArray<Location> locations, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis) : base(owner, parameterType, ordinal, refKind, name, locations) { Debug.Assert((syntaxRef == null) || (syntaxRef.GetSyntax().IsKind(SyntaxKind.Parameter))); _lazyHasOptionalAttribute = ThreeState.Unknown; _syntaxRef = syntaxRef; if (isParams) { _parameterSyntaxKind |= ParameterSyntaxKind.ParamsParameter; } if (isExtensionMethodThis) { _parameterSyntaxKind |= ParameterSyntaxKind.ExtensionThisParameter; } var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax != null && parameterSyntax.Default != null) { _parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter; } _lazyDefaultSyntaxValue = ConstantValue.Unset; } private Binder ParameterBinderOpt => (ContainingSymbol as SourceMethodSymbolWithAttributes)?.ParameterBinder; internal sealed override SyntaxReference SyntaxReference => _syntaxRef; private ParameterSyntax CSharpSyntaxNode => (ParameterSyntax)_syntaxRef?.GetSyntax(); public override bool IsDiscard => false; internal sealed override ConstantValue ExplicitDefaultConstantValue { get { // Parameter has either default argument syntax or DefaultParameterValue attribute, but not both. // We separate these since in some scenarios (delegate Invoke methods) we need to suppress syntactic // default value but use value from pseudo-custom attribute. // // For example: // public delegate void D([Optional, DefaultParameterValue(1)]int a, int b = 2); // // Dev11 emits the first parameter as option with default value and the second as regular parameter. // The syntactic default value is suppressed since additional synthesized parameters are added at the end of the signature. return DefaultSyntaxValue ?? DefaultValueFromAttributes; } } internal sealed override ConstantValue DefaultValueFromAttributes { get { ParameterEarlyWellKnownAttributeData data = GetEarlyDecodedWellKnownAttributeData(); return (data != null && data.DefaultParameterValue != ConstantValue.Unset) ? data.DefaultParameterValue : ConstantValue.NotAvailable; } } internal sealed override bool IsIDispatchConstant => GetDecodedWellKnownAttributeData()?.HasIDispatchConstantAttribute == true; internal override bool IsIUnknownConstant => GetDecodedWellKnownAttributeData()?.HasIUnknownConstantAttribute == true; internal override bool IsCallerLineNumber => GetEarlyDecodedWellKnownAttributeData()?.HasCallerLineNumberAttribute == true; internal override bool IsCallerFilePath => GetEarlyDecodedWellKnownAttributeData()?.HasCallerFilePathAttribute == true; internal override bool IsCallerMemberName => GetEarlyDecodedWellKnownAttributeData()?.HasCallerMemberNameAttribute == true; internal override int CallerArgumentExpressionParameterIndex { get { return GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex ?? -1; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => (GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments).NullToEmpty(); internal override bool HasInterpolatedStringHandlerArgumentError => GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments.IsDefault ?? false; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData()); } } private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(ParameterWellKnownAttributeData attributeData) { if (attributeData == null) { return FlowAnalysisAnnotations.None; } FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None; if (attributeData.HasAllowNullAttribute) annotations |= FlowAnalysisAnnotations.AllowNull; if (attributeData.HasDisallowNullAttribute) annotations |= FlowAnalysisAnnotations.DisallowNull; if (attributeData.HasMaybeNullAttribute) { annotations |= FlowAnalysisAnnotations.MaybeNull; } else { if (attributeData.MaybeNullWhenAttribute is bool when) { annotations |= (when ? FlowAnalysisAnnotations.MaybeNullWhenTrue : FlowAnalysisAnnotations.MaybeNullWhenFalse); } } if (attributeData.HasNotNullAttribute) { annotations |= FlowAnalysisAnnotations.NotNull; } else { if (attributeData.NotNullWhenAttribute is bool when) { annotations |= (when ? FlowAnalysisAnnotations.NotNullWhenTrue : FlowAnalysisAnnotations.NotNullWhenFalse); } } if (attributeData.DoesNotReturnIfAttribute is bool condition) { annotations |= (condition ? FlowAnalysisAnnotations.DoesNotReturnIfTrue : FlowAnalysisAnnotations.DoesNotReturnIfFalse); } return annotations; } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => GetDecodedWellKnownAttributeData()?.NotNullIfParameterNotNull ?? ImmutableHashSet<string>.Empty; internal bool HasEnumeratorCancellationAttribute { get { ParameterWellKnownAttributeData attributeData = GetDecodedWellKnownAttributeData(); return attributeData?.HasEnumeratorCancellationAttribute == true; } } #nullable enable internal static SyntaxNode? GetDefaultValueSyntaxForIsNullableAnalysisEnabled(ParameterSyntax? parameterSyntax) => parameterSyntax?.Default?.Value; private ConstantValue DefaultSyntaxValue { get { if (state.NotePartComplete(CompletionPart.StartDefaultSyntaxValue)) { var diagnostics = BindingDiagnosticBag.GetInstance(); Debug.Assert(diagnostics.DiagnosticBag != null); var previousValue = Interlocked.CompareExchange( ref _lazyDefaultSyntaxValue, MakeDefaultExpression(diagnostics, out var binder, out var parameterEqualsValue), ConstantValue.Unset); Debug.Assert(previousValue == ConstantValue.Unset); var completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValue); Debug.Assert(completedOnThisThread); if (parameterEqualsValue is not null) { if (binder is not null && GetDefaultValueSyntaxForIsNullableAnalysisEnabled(CSharpSyntaxNode) is { } valueSyntax) { NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, valueSyntax, diagnostics.DiagnosticBag); } if (!_lazyDefaultSyntaxValue.IsBad) { VerifyParamDefaultValueMatchesAttributeIfAny(_lazyDefaultSyntaxValue, parameterEqualsValue.Value.Syntax, diagnostics); } } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValueDiagnostics); Debug.Assert(completedOnThisThread); } state.SpinWaitComplete(CompletionPart.EndDefaultSyntaxValue, default(CancellationToken)); return _lazyDefaultSyntaxValue; } } private Binder GetBinder(SyntaxNode syntax) { var binder = ParameterBinderOpt; // If binder is null, then get it from the compilation. Otherwise use the provided binder. // Don't always get it from the compilation because we might be in a speculative context (local function parameter), // in which case the declaring compilation is the wrong one. if (binder == null) { var compilation = this.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); binder = binderFactory.GetBinder(syntax); } Debug.Assert(binder.GetBinder(syntax) == null); return binder; } private void NullableAnalyzeParameterDefaultValueFromAttributes() { var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax == null) { // If there is no syntax at all for the parameter, it means we are in a situation like // a property setter whose 'value' parameter has a default value from attributes. // There isn't a sensible use for this in the language, so we just bail in such scenarios. return; } // The syntax span used to determine whether the attribute value is in a nullable-enabled // context is larger than necessary - it includes the entire attribute list rather than the specific // default value attribute which is used in AttributeSemanticModel.IsNullableAnalysisEnabled(). var attributes = parameterSyntax.AttributeLists.Node; if (attributes is null || !NullableWalker.NeedsAnalysis(DeclaringCompilation, attributes)) { return; } var defaultValue = DefaultValueFromAttributes; if (defaultValue == null || defaultValue.IsBad) { return; } var binder = GetBinder(parameterSyntax); // Nullable warnings *within* the attribute argument (such as a W-warning for `(string)null`) // are reported when we nullable-analyze attribute arguments separately from here. // However, this analysis of the constant value's compatibility with the parameter // needs to wait until the attributes are populated on the parameter symbol. var parameterEqualsValue = new BoundParameterEqualsValue( parameterSyntax, this, ImmutableArray<LocalSymbol>.Empty, // note that if the parameter type conflicts with the default value from attributes, // we will just get a bad constant value above and return early. new BoundLiteral(parameterSyntax, defaultValue, Type)); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Debug.Assert(diagnostics.DiagnosticBag != null); NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, parameterSyntax, diagnostics.DiagnosticBag); AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); } // This method *must not* depend on attributes on the parameter symbol. // Otherwise we will have cycles when binding usage of attributes whose constructors have optional parameters private ConstantValue MakeDefaultExpression(BindingDiagnosticBag diagnostics, out Binder? binder, out BoundParameterEqualsValue? parameterEqualsValue) { binder = null; parameterEqualsValue = null; var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax == null) { return ConstantValue.NotAvailable; } var defaultSyntax = parameterSyntax.Default; if (defaultSyntax == null) { return ConstantValue.NotAvailable; } binder = GetBinder(defaultSyntax); Binder binderForDefault = binder.CreateBinderForParameterDefaultValue(this, defaultSyntax); Debug.Assert(binderForDefault.InParameterDefaultValue); Debug.Assert(binderForDefault.ContainingMemberOrLambda == ContainingSymbol); parameterEqualsValue = binderForDefault.BindParameterDefaultValue(defaultSyntax, this, diagnostics, out var valueBeforeConversion); if (valueBeforeConversion.HasErrors) { return ConstantValue.Bad; } BoundExpression convertedExpression = parameterEqualsValue.Value; bool hasErrors = ParameterHelpers.ReportDefaultParameterErrors(binder, ContainingSymbol, parameterSyntax, this, valueBeforeConversion, convertedExpression, diagnostics); if (hasErrors) { return ConstantValue.Bad; } // If we have something like M(double? x = 1) then the expression we'll get is (double?)1, which // does not have a constant value. The constant value we want is (double)1. // The default literal conversion is an exception: (double)default would give the wrong value for M(double? x = default). if (convertedExpression.ConstantValue == null && convertedExpression.Kind == BoundKind.Conversion && ((BoundConversion)convertedExpression).ConversionKind != ConversionKind.DefaultLiteral) { if (parameterType.Type.IsNullableType()) { convertedExpression = binder.GenerateConversionForAssignment(parameterType.Type.GetNullableUnderlyingType(), valueBeforeConversion, diagnostics, isDefaultParameter: true); } } // represent default(struct) by a Null constant: var value = convertedExpression.ConstantValue ?? ConstantValue.Null; return value; } #nullable disable public override string MetadataName { get { // The metadata parameter name should be the name used in the partial definition. var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return base.MetadataName; } var definition = sourceMethod.SourcePartialDefinition; if ((object)definition == null) { return base.MetadataName; } return definition.Parameters[this.Ordinal].MetadataName; } } protected virtual IAttributeTargetSymbol AttributeOwner => this; IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner; AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Parameter; AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { if (SynthesizedRecordPropertySymbol.HaveCorrespondingSynthesizedRecordPropertySymbol(this)) { return AttributeLocation.Parameter | AttributeLocation.Property | AttributeLocation.Field; } return AttributeLocation.Parameter; } } /// <summary> /// Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source parameter symbols. /// </summary> /// <remarks> /// Used for parameters of partial implementation. We bind the attributes only on the definition /// part and copy them over to the implementation. /// </remarks> private SourceParameterSymbol BoundAttributesSource { get { var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return null; } var impl = sourceMethod.SourcePartialImplementation; if ((object)impl == null) { return null; } return (SourceParameterSymbol)impl.Parameters[this.Ordinal]; } } internal sealed override SyntaxList<AttributeListSyntax> AttributeDeclarationList { get { var syntax = this.CSharpSyntaxNode; return (syntax != null) ? syntax.AttributeLists : default(SyntaxList<AttributeListSyntax>); } } /// <summary> /// Gets the syntax list of custom attributes that declares attributes for this parameter symbol. /// </summary> internal virtual OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // C# spec: // The attributes on the parameters of the resulting method declaration // are the combined attributes of the corresponding parameters of the defining // and the implementing partial method declaration in unspecified order. // Duplicates are not removed. SyntaxList<AttributeListSyntax> attributes = AttributeDeclarationList; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return OneOrMany.Create(attributes); } SyntaxList<AttributeListSyntax> otherAttributes; // if this is a definition get the implementation and vice versa SourceOrdinaryMethodSymbol otherPart = sourceMethod.OtherPartOfPartial; if ((object)otherPart != null) { otherAttributes = ((SourceParameterSymbol)otherPart.Parameters[this.Ordinal]).AttributeDeclarationList; } else { otherAttributes = default(SyntaxList<AttributeListSyntax>); } if (attributes.Equals(default(SyntaxList<AttributeListSyntax>))) { return OneOrMany.Create(otherAttributes); } else if (otherAttributes.Equals(default(SyntaxList<AttributeListSyntax>))) { return OneOrMany.Create(attributes); } return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)); } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal ParameterWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ParameterWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } /// <summary> /// Returns data decoded from special 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> internal ParameterEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ParameterEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal sealed override CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { SourceParameterSymbol copyFrom = this.BoundAttributesSource; // prevent infinite recursion: Debug.Assert(!ReferenceEquals(copyFrom, this)); bool bagCreatedOnThisThread; if ((object)copyFrom != null) { var attributesBag = copyFrom.GetAttributesBag(); bagCreatedOnThisThread = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } else { var attributeSyntax = this.GetAttributeDeclarations(); bagCreatedOnThisThread = LoadAndValidateAttributes(attributeSyntax, ref _lazyCustomAttributesBag, binderOpt: ParameterBinderOpt); } if (bagCreatedOnThisThread) { NullableAnalyzeParameterDefaultValueFromAttributes(); state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EarlyDecodeWellKnownAttributeType(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax) { Debug.Assert(!attributeType.IsErrorType()); // NOTE: OptionalAttribute is decoded specially before any of the other attributes and stored in the parameter // symbol (rather than in the EarlyWellKnownAttributeData) because it is needed during overload resolution. if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.OptionalAttribute)) { _lazyHasOptionalAttribute = ThreeState.True; } } internal override void PostEarlyDecodeWellKnownAttributeTypes() { if (_lazyHasOptionalAttribute == ThreeState.Unknown) { _lazyHasOptionalAttribute = ThreeState.False; } base.PostEarlyDecodeWellKnownAttributeTypes(); } internal override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, ref arguments); } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, ref arguments); } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, ref arguments); } else if (!IsOnPartialImplementation(arguments.AttributeSyntax)) { if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerLineNumberAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerFilePathAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerMemberNameAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute)) { var index = -1; var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out _); if (!attribute.HasErrors) { var constructorArguments = attribute.CommonConstructorArguments; Debug.Assert(constructorArguments.Length == 1); if (constructorArguments[0].TryDecodeValue(SpecialType.System_String, out string parameterName)) { var parameters = ContainingSymbol.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].Name.Equals(parameterName, StringComparison.Ordinal)) { index = i; break; } } } } arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().CallerArgumentExpressionParameterIndex = index; } } return base.EarlyDecodeWellKnownAttribute(ref arguments); } private CSharpAttributeData EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription description, ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) || description.Equals(AttributeDescription.DecimalConstantAttribute) || description.Equals(AttributeDescription.DateTimeConstantAttribute)); bool hasAnyDiagnostics; var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); ConstantValue value; if (attribute.HasErrors) { value = ConstantValue.Bad; hasAnyDiagnostics = true; } else { value = DecodeDefaultParameterValueAttribute(description, attribute, arguments.AttributeSyntax, diagnose: false, diagnosticsOpt: null); } var paramData = arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>(); if (paramData.DefaultParameterValue == ConstantValue.Unset) { paramData.DefaultParameterValue = value; } return !hasAnyDiagnostics ? attribute : null; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); Debug.Assert(AttributeDescription.InterpolatedStringHandlerArgumentAttribute.Signatures.Length == 2); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultParameterValueAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.OptionalAttribute)) { Debug.Assert(_lazyHasOptionalAttribute == ThreeState.True); if (HasDefaultArgumentSyntax) { // error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute diagnostics.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, arguments.AttributeSyntaxOpt.Name.Location); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.ParamArrayAttribute)) { // error CS0674: Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead. diagnostics.Add(ErrorCode.ERR_ExplicitParamArray, arguments.AttributeSyntaxOpt.Name.Location); } else if (attribute.IsTargetAttribute(this, AttributeDescription.InAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasInAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.OutAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasOutAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute)) { MarshalAsAttributeDecoder<ParameterWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>.Decode(ref arguments, AttributeTargets.Parameter, MessageProvider.Instance); } else if (attribute.IsTargetAttribute(this, AttributeDescription.IDispatchConstantAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIDispatchConstantAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.IUnknownConstantAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIUnknownConstantAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerLineNumberAttribute)) { ValidateCallerLineNumberAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerFilePathAttribute)) { ValidateCallerFilePathAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerMemberNameAttribute)) { ValidateCallerMemberNameAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerArgumentExpressionAttribute)) { ValidateCallerArgumentExpressionAttribute(arguments.AttributeSyntaxOpt, attribute, diagnostics); } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasAllowNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasDisallowNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasMaybeNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullWhenAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().MaybeNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.MaybeNullWhenAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasNotNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullWhenAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().NotNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.NotNullWhenAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DoesNotReturnIfAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().DoesNotReturnIfAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.DoesNotReturnIfAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullIfNotNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().AddNotNullIfParameterNotNull(attribute.DecodeNotNullIfNotNullAttribute()); } else if (attribute.IsTargetAttribute(this, AttributeDescription.EnumeratorCancellationAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasEnumeratorCancellationAttribute = true; ValidateCancellationTokenAttribute(arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); } else if (attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.InterpolatedStringHandlerArgumentAttribute) is (0 or 1) and var index) { DecodeInterpolatedStringHandlerArgumentAttribute(ref arguments, diagnostics, index); } } private static bool? DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription description, CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_Boolean, out bool value) ? (bool?)value : null; } private void DecodeDefaultParameterValueAttribute(AttributeDescription description, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { var attribute = arguments.Attribute; var syntax = arguments.AttributeSyntaxOpt; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); var value = DecodeDefaultParameterValueAttribute(description, attribute, syntax, diagnose: true, diagnosticsOpt: diagnostics); if (!value.IsBad) { VerifyParamDefaultValueMatchesAttributeIfAny(value, syntax, diagnostics); } } /// <summary> /// Verify the default value matches the default value from any earlier attribute /// (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). /// If not, report ERR_ParamDefaultValueDiffersFromAttribute. /// </summary> private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { var data = GetEarlyDecodedWellKnownAttributeData(); if (data != null) { var attrValue = data.DefaultParameterValue; if ((attrValue != ConstantValue.Unset) && (value != attrValue)) { // CS8017: The parameter has multiple distinct default values. diagnostics.Add(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, syntax.Location); } } } private ConstantValue DecodeDefaultParameterValueAttribute(AttributeDescription description, CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) { Debug.Assert(!attribute.HasErrors); if (description.Equals(AttributeDescription.DefaultParameterValueAttribute)) { return DecodeDefaultParameterValueAttribute(attribute, node, diagnose, diagnosticsOpt); } else if (description.Equals(AttributeDescription.DecimalConstantAttribute)) { return attribute.DecodeDecimalConstantValue(); } else { Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute)); return attribute.DecodeDateTimeConstantValue(); } } private ConstantValue DecodeDefaultParameterValueAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) { Debug.Assert(!diagnose || diagnosticsOpt != null); if (HasDefaultArgumentSyntax) { // error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, node.Name.Location); } return ConstantValue.Bad; } // BREAK: In dev10, DefaultParameterValueAttribute could not be applied to System.Type or array parameters. // When this was attempted, dev10 produced CS1909, ERR_DefaultValueBadParamType. Roslyn takes a different // approach: instead of looking at the parameter type, we look at the argument type. There's nothing wrong // with providing a default value for a System.Type or array parameter, as long as the default parameter // is not a System.Type or an array (i.e. null is fine). Since we are no longer interested in the type of // the parameter, all occurrences of CS1909 have been replaced with CS1910, ERR_DefaultValueBadValueType, // to indicate that the argument type, rather than the parameter type, is the source of the problem. Debug.Assert(attribute.CommonConstructorArguments.Length == 1); // the type of the value is the type of the expression in the attribute: var arg = attribute.CommonConstructorArguments[0]; SpecialType specialType = arg.Kind == TypedConstantKind.Enum ? ((NamedTypeSymbol)arg.TypeInternal).EnumUnderlyingType.SpecialType : arg.TypeInternal.SpecialType; var compilation = this.DeclaringCompilation; var constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnosticsOpt, ContainingAssembly); if (constantValueDiscriminator == ConstantValueTypeDiscriminator.Bad) { if (arg.Kind != TypedConstantKind.Array && arg.ValueInternal == null) { if (this.Type.IsReferenceType) { constantValueDiscriminator = ConstantValueTypeDiscriminator.Null; } else { // error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location); } return ConstantValue.Bad; } } else { // error CS1910: Argument of type '{0}' is not applicable for the DefaultParameterValue attribute if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueBadValueType, node.Name.Location, arg.TypeInternal); } return ConstantValue.Bad; } } else if (!compilation.Conversions.ClassifyConversionFromType((TypeSymbol)arg.TypeInternal, this.Type, ref useSiteInfo).Kind.IsImplicitConversion()) { // error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location); diagnosticsOpt.Add(node.Name.Location, useSiteInfo); } return ConstantValue.Bad; } if (diagnose) { diagnosticsOpt.Add(node.Name.Location, useSiteInfo); } return ConstantValue.Create(arg.ValueInternal, constantValueDiscriminator); } private bool IsValidCallerInfoContext(AttributeSyntax node) => !ContainingSymbol.IsExplicitInterfaceImplementation() && !ContainingSymbol.IsOperator() && !IsOnPartialImplementation(node); /// <summary> /// Is the attribute syntax appearing on a parameter of a partial method implementation part? /// Since attributes are merged between the parts of a partial, we need to look at the syntax where the /// attribute appeared in the source to see if it corresponds to a partial method implementation part. /// </summary> /// <param name="node"></param> /// <returns></returns> private bool IsOnPartialImplementation(AttributeSyntax node) { var method = ContainingSymbol as MethodSymbol; if ((object)method == null) return false; var impl = method.IsPartialImplementation() ? method : method.PartialImplementationPart; if ((object)impl == null) return false; var paramList = node // AttributeSyntax .Parent // AttributeListSyntax .Parent // ParameterSyntax .Parent as ParameterListSyntax; // ParameterListSyntax if (paramList == null) return false; var methDecl = paramList.Parent as MethodDeclarationSyntax; if (methDecl == null) return false; foreach (var r in impl.DeclaringSyntaxReferences) { if (r.GetSyntax() == methDecl) return true; } return false; } private void ValidateCallerLineNumberAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4024: The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerLineNumberConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol intType = compilation.GetSpecialType(SpecialType.System_Int32); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerLineNumberParam, node.Name.Location, intType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4020: The CallerLineNumberAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerLineNumberParamWithoutDefaultValue, node.Name.Location); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerFilePathAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4025: The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4018: CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerFilePathParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4021: The CallerFilePathAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerFilePathParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS7082: The CallerFilePathAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerMemberNameAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4026: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerMemberNameParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4022: The CallerMemberNameAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerMemberNameParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS7081: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerFilePath) { // CS7080: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerArgumentExpressionAttribute(AttributeSyntax node, CSharpAttributeData attribute, BindingDiagnosticBag diagnostics) { // We intentionally don't report an error for earlier language versions here. The attribute already existed // before the feature was developed. The error is only reported when the binder supplies a value // based on the attribute. CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS8966: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS8959: CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerArgumentExpressionParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS8964: The CallerArgumentExpressionAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerArgumentExpressionParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS8960: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerFilePath) { // CS8961: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerMemberName) { // CS8962: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute. diagnostics.Add(ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (attribute.CommonConstructorArguments.Length == 1 && GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex == -1) { // CS8963: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name. diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex == Ordinal) { // CS8965: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential. diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCancellationTokenAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { if (needsReporting()) { diagnostics.Add(ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } bool needsReporting() { if (!Type.Equals(this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Threading_CancellationToken))) { return true; } else if (this.ContainingSymbol is MethodSymbol method && method.IsAsync && method.ReturnType.OriginalDefinition.Equals(this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T))) { // Note: async methods that return this type must be iterators. This is enforced elsewhere return false; } return true; } } #nullable enable private void DecodeInterpolatedStringHandlerArgumentAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, BindingDiagnosticBag diagnostics, int attributeIndex) { Debug.Assert(attributeIndex is 0 or 1); Debug.Assert(arguments.Attribute.IsTargetAttribute(this, AttributeDescription.InterpolatedStringHandlerArgumentAttribute) && arguments.Attribute.CommonConstructorArguments.Length == 1); Debug.Assert(arguments.AttributeSyntaxOpt is not null); var errorLocation = arguments.AttributeSyntaxOpt.Location; if (Type is not NamedTypeSymbol { IsInterpolatedStringHandlerType: true } handlerType) { // '{0}' is not an interpolated string handler type. diagnostics.Add(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, errorLocation, Type); setInterpolatedStringHandlerAttributeError(ref arguments); return; } TypedConstant constructorArgument = arguments.Attribute.CommonConstructorArguments[0]; ImmutableArray<ParameterSymbol> containingSymbolParameters = ContainingSymbol.GetParameters(); ImmutableArray<int> parameterOrdinals; ArrayBuilder<ParameterSymbol?> parameters; if (attributeIndex == 0) { if (decodeName(constructorArgument, ref arguments) is not (int ordinal, var parameter)) { // If an error needs to be reported, it will already have been reported by another step. setInterpolatedStringHandlerAttributeError(ref arguments); return; } parameterOrdinals = ImmutableArray.Create(ordinal); parameters = ArrayBuilder<ParameterSymbol?>.GetInstance(1); parameters.Add(parameter); } else if (attributeIndex == 1) { bool hadError = false; parameters = ArrayBuilder<ParameterSymbol?>.GetInstance(constructorArgument.Values.Length); var ordinalsBuilder = ArrayBuilder<int>.GetInstance(constructorArgument.Values.Length); foreach (var nestedArgument in constructorArgument.Values) { if (decodeName(nestedArgument, ref arguments) is (int ordinal, var parameter) && !hadError) { parameters.Add(parameter); ordinalsBuilder.Add(ordinal); } else { hadError = true; } } if (hadError) { parameters.Free(); ordinalsBuilder.Free(); setInterpolatedStringHandlerAttributeError(ref arguments); return; } parameterOrdinals = ordinalsBuilder.ToImmutableAndFree(); } else { throw ExceptionUtilities.Unreachable; } var parameterWellKnownAttributeData = arguments.GetOrCreateData<ParameterWellKnownAttributeData>(); parameterWellKnownAttributeData.InterpolatedStringHandlerArguments = parameterOrdinals; (int Ordinal, ParameterSymbol? Parameter)? decodeName(TypedConstant constant, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert(arguments.AttributeSyntaxOpt is not null); if (constant.IsNull) { // null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. diagnostics.Add(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location); return null; } if (constant.TypeInternal is not { SpecialType: SpecialType.System_String }) { // There has already been an error reported. Just return null. return null; } var name = constant.DecodeValue<string>(SpecialType.System_String); Debug.Assert(name != null); if (name == "") { // Name refers to the "this" instance parameter. if (!ContainingSymbol.RequiresInstanceReceiver() || ContainingSymbol is MethodSymbol { MethodKind: MethodKind.Constructor }) { // '{0}' is not an instance method, the receiver cannot be an interpolated string handler argument. diagnostics.Add(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location, ContainingSymbol); return null; } return (BoundInterpolatedStringArgumentPlaceholder.InstanceParameter, null); } var parameter = containingSymbolParameters.FirstOrDefault(static (param, name) => string.Equals(param.Name, name, StringComparison.Ordinal), name); if (parameter is null) { // '{0}' is not a valid parameter name from '{1}'. diagnostics.Add(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location, name, ContainingSymbol); return null; } if ((object)parameter == this) { // InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. diagnostics.Add(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, errorLocation); return null; } if (parameter.Ordinal > Ordinal) { // Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. // This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated // string handler parameter after all arguments involved. diagnostics.Add(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, errorLocation, parameter.Name, this); } return (parameter.Ordinal, parameter); } static void setInterpolatedStringHandlerAttributeError(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().InterpolatedStringHandlerArguments = default; } } #nullable disable internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) { Debug.Assert(!boundAttributes.IsDefault); Debug.Assert(!allAttributeSyntaxNodes.IsDefault); Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length); Debug.Assert(_lazyCustomAttributesBag != null); Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed); Debug.Assert(symbolPart == AttributeLocation.None); var data = (ParameterWellKnownAttributeData)decodedData; if (data != null) { switch (RefKind) { case RefKind.Ref: if (data.HasOutAttribute && !data.HasInAttribute) { // error CS0662: Cannot specify the Out attribute on a ref parameter without also specifying the In attribute. diagnostics.Add(ErrorCode.ERR_OutAttrOnRefParam, this.Locations[0]); } break; case RefKind.Out: if (data.HasInAttribute) { // error CS0036: An out parameter cannot have the In attribute. diagnostics.Add(ErrorCode.ERR_InAttrOnOutParam, this.Locations[0]); } break; case RefKind.In: if (data.HasOutAttribute) { // error CS8355: An in parameter cannot have the Out attribute. diagnostics.Add(ErrorCode.ERR_OutAttrOnInParam, this.Locations[0]); } break; } } base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); } /// <summary> /// True if the parameter has default argument syntax. /// </summary> internal override bool HasDefaultArgumentSyntax { get { return (_parameterSyntaxKind & ParameterSyntaxKind.DefaultParameter) != 0; } } /// <summary> /// True if the parameter is marked by <see cref="System.Runtime.InteropServices.OptionalAttribute"/>. /// </summary> internal sealed override bool HasOptionalAttribute { get { if (_lazyHasOptionalAttribute == ThreeState.Unknown) { SourceParameterSymbol copyFrom = this.BoundAttributesSource; // prevent infinite recursion: Debug.Assert(!ReferenceEquals(copyFrom, this)); if ((object)copyFrom != null) { // Parameter of partial implementation. // We bind the attributes only on the definition part and copy them over to the implementation. _lazyHasOptionalAttribute = copyFrom.HasOptionalAttribute.ToThreeState(); } else { // lazyHasOptionalAttribute is decoded early, hence we cannot reach here when binding attributes for this symbol. // So it is fine to force complete attributes here. var attributes = GetAttributes(); if (!attributes.Any()) { _lazyHasOptionalAttribute = ThreeState.False; } } } Debug.Assert(_lazyHasOptionalAttribute.HasValue()); return _lazyHasOptionalAttribute.Value(); } } internal override bool IsMetadataOptional { get { // NOTE: IsMetadataOptional property can be invoked during overload resolution. // NOTE: Optional attribute is decoded very early in attribute binding phase, see method EarlyDecodeOptionalAttribute // NOTE: If you update the below check to look for any more attributes, make sure that they are decoded early. return HasDefaultArgumentSyntax || HasOptionalAttribute; } } internal sealed override bool IsMetadataIn => base.IsMetadataIn || GetDecodedWellKnownAttributeData()?.HasInAttribute == true; internal sealed override bool IsMetadataOut => base.IsMetadataOut || GetDecodedWellKnownAttributeData()?.HasOutAttribute == true; internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation => GetDecodedWellKnownAttributeData()?.MarshallingInformation; public override bool IsParams => (_parameterSyntaxKind & ParameterSyntaxKind.ParamsParameter) != 0; internal override bool IsExtensionMethodThis => (_parameterSyntaxKind & ParameterSyntaxKind.ExtensionThisParameter) != 0; public override ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { _ = this.GetAttributes(); _ = this.ExplicitDefaultConstantValue; state.SpinWaitComplete(CompletionPart.ComplexParameterSymbolAll, cancellationToken); } } internal sealed class SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef : SourceComplexParameterSymbol { private readonly ImmutableArray<CustomModifier> _refCustomModifiers; internal SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, string name, ImmutableArray<Location> locations, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis) : base(owner, ordinal, parameterType, refKind, name, locations, syntaxRef, isParams, isExtensionMethodThis) { Debug.Assert(!refCustomModifiers.IsEmpty); _refCustomModifiers = refCustomModifiers; Debug.Assert(refKind != RefKind.None || _refCustomModifiers.IsEmpty); } public override ImmutableArray<CustomModifier> RefCustomModifiers => _refCustomModifiers; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A source parameter, potentially with a default value, attributes, etc. /// </summary> internal class SourceComplexParameterSymbol : SourceParameterSymbol, IAttributeTargetSymbol { [Flags] private enum ParameterSyntaxKind : byte { Regular = 0, ParamsParameter = 1, ExtensionThisParameter = 2, DefaultParameter = 4, } private readonly SyntaxReference _syntaxRef; private readonly ParameterSyntaxKind _parameterSyntaxKind; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ThreeState _lazyHasOptionalAttribute; protected ConstantValue _lazyDefaultSyntaxValue; internal SourceComplexParameterSymbol( Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, string name, ImmutableArray<Location> locations, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis) : base(owner, parameterType, ordinal, refKind, name, locations) { Debug.Assert((syntaxRef == null) || (syntaxRef.GetSyntax().IsKind(SyntaxKind.Parameter))); _lazyHasOptionalAttribute = ThreeState.Unknown; _syntaxRef = syntaxRef; if (isParams) { _parameterSyntaxKind |= ParameterSyntaxKind.ParamsParameter; } if (isExtensionMethodThis) { _parameterSyntaxKind |= ParameterSyntaxKind.ExtensionThisParameter; } var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax != null && parameterSyntax.Default != null) { _parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter; } _lazyDefaultSyntaxValue = ConstantValue.Unset; } private Binder ParameterBinderOpt => (ContainingSymbol as SourceMethodSymbolWithAttributes)?.ParameterBinder; internal sealed override SyntaxReference SyntaxReference => _syntaxRef; private ParameterSyntax CSharpSyntaxNode => (ParameterSyntax)_syntaxRef?.GetSyntax(); public override bool IsDiscard => false; internal sealed override ConstantValue ExplicitDefaultConstantValue { get { // Parameter has either default argument syntax or DefaultParameterValue attribute, but not both. // We separate these since in some scenarios (delegate Invoke methods) we need to suppress syntactic // default value but use value from pseudo-custom attribute. // // For example: // public delegate void D([Optional, DefaultParameterValue(1)]int a, int b = 2); // // Dev11 emits the first parameter as option with default value and the second as regular parameter. // The syntactic default value is suppressed since additional synthesized parameters are added at the end of the signature. return DefaultSyntaxValue ?? DefaultValueFromAttributes; } } internal sealed override ConstantValue DefaultValueFromAttributes { get { ParameterEarlyWellKnownAttributeData data = GetEarlyDecodedWellKnownAttributeData(); return (data != null && data.DefaultParameterValue != ConstantValue.Unset) ? data.DefaultParameterValue : ConstantValue.NotAvailable; } } internal sealed override bool IsIDispatchConstant => GetDecodedWellKnownAttributeData()?.HasIDispatchConstantAttribute == true; internal override bool IsIUnknownConstant => GetDecodedWellKnownAttributeData()?.HasIUnknownConstantAttribute == true; internal override bool IsCallerLineNumber => GetEarlyDecodedWellKnownAttributeData()?.HasCallerLineNumberAttribute == true; internal override bool IsCallerFilePath => GetEarlyDecodedWellKnownAttributeData()?.HasCallerFilePathAttribute == true; internal override bool IsCallerMemberName => GetEarlyDecodedWellKnownAttributeData()?.HasCallerMemberNameAttribute == true; internal override int CallerArgumentExpressionParameterIndex { get { return GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex ?? -1; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => (GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments).NullToEmpty(); internal override bool HasInterpolatedStringHandlerArgumentError => GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments.IsDefault ?? false; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData()); } } private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(ParameterWellKnownAttributeData attributeData) { if (attributeData == null) { return FlowAnalysisAnnotations.None; } FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None; if (attributeData.HasAllowNullAttribute) annotations |= FlowAnalysisAnnotations.AllowNull; if (attributeData.HasDisallowNullAttribute) annotations |= FlowAnalysisAnnotations.DisallowNull; if (attributeData.HasMaybeNullAttribute) { annotations |= FlowAnalysisAnnotations.MaybeNull; } else { if (attributeData.MaybeNullWhenAttribute is bool when) { annotations |= (when ? FlowAnalysisAnnotations.MaybeNullWhenTrue : FlowAnalysisAnnotations.MaybeNullWhenFalse); } } if (attributeData.HasNotNullAttribute) { annotations |= FlowAnalysisAnnotations.NotNull; } else { if (attributeData.NotNullWhenAttribute is bool when) { annotations |= (when ? FlowAnalysisAnnotations.NotNullWhenTrue : FlowAnalysisAnnotations.NotNullWhenFalse); } } if (attributeData.DoesNotReturnIfAttribute is bool condition) { annotations |= (condition ? FlowAnalysisAnnotations.DoesNotReturnIfTrue : FlowAnalysisAnnotations.DoesNotReturnIfFalse); } return annotations; } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => GetDecodedWellKnownAttributeData()?.NotNullIfParameterNotNull ?? ImmutableHashSet<string>.Empty; internal bool HasEnumeratorCancellationAttribute { get { ParameterWellKnownAttributeData attributeData = GetDecodedWellKnownAttributeData(); return attributeData?.HasEnumeratorCancellationAttribute == true; } } #nullable enable internal static SyntaxNode? GetDefaultValueSyntaxForIsNullableAnalysisEnabled(ParameterSyntax? parameterSyntax) => parameterSyntax?.Default?.Value; private ConstantValue DefaultSyntaxValue { get { if (state.NotePartComplete(CompletionPart.StartDefaultSyntaxValue)) { var diagnostics = BindingDiagnosticBag.GetInstance(); Debug.Assert(diagnostics.DiagnosticBag != null); var previousValue = Interlocked.CompareExchange( ref _lazyDefaultSyntaxValue, MakeDefaultExpression(diagnostics, out var binder, out var parameterEqualsValue), ConstantValue.Unset); Debug.Assert(previousValue == ConstantValue.Unset); var completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValue); Debug.Assert(completedOnThisThread); if (parameterEqualsValue is not null) { if (binder is not null && GetDefaultValueSyntaxForIsNullableAnalysisEnabled(CSharpSyntaxNode) is { } valueSyntax) { NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, valueSyntax, diagnostics.DiagnosticBag); } if (!_lazyDefaultSyntaxValue.IsBad) { VerifyParamDefaultValueMatchesAttributeIfAny(_lazyDefaultSyntaxValue, parameterEqualsValue.Value.Syntax, diagnostics); } } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValueDiagnostics); Debug.Assert(completedOnThisThread); } state.SpinWaitComplete(CompletionPart.EndDefaultSyntaxValue, default(CancellationToken)); return _lazyDefaultSyntaxValue; } } private Binder GetBinder(SyntaxNode syntax) { var binder = ParameterBinderOpt; // If binder is null, then get it from the compilation. Otherwise use the provided binder. // Don't always get it from the compilation because we might be in a speculative context (local function parameter), // in which case the declaring compilation is the wrong one. if (binder == null) { var compilation = this.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); binder = binderFactory.GetBinder(syntax); } Debug.Assert(binder.GetBinder(syntax) == null); return binder; } private void NullableAnalyzeParameterDefaultValueFromAttributes() { var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax == null) { // If there is no syntax at all for the parameter, it means we are in a situation like // a property setter whose 'value' parameter has a default value from attributes. // There isn't a sensible use for this in the language, so we just bail in such scenarios. return; } // The syntax span used to determine whether the attribute value is in a nullable-enabled // context is larger than necessary - it includes the entire attribute list rather than the specific // default value attribute which is used in AttributeSemanticModel.IsNullableAnalysisEnabled(). var attributes = parameterSyntax.AttributeLists.Node; if (attributes is null || !NullableWalker.NeedsAnalysis(DeclaringCompilation, attributes)) { return; } var defaultValue = DefaultValueFromAttributes; if (defaultValue == null || defaultValue.IsBad) { return; } var binder = GetBinder(parameterSyntax); // Nullable warnings *within* the attribute argument (such as a W-warning for `(string)null`) // are reported when we nullable-analyze attribute arguments separately from here. // However, this analysis of the constant value's compatibility with the parameter // needs to wait until the attributes are populated on the parameter symbol. var parameterEqualsValue = new BoundParameterEqualsValue( parameterSyntax, this, ImmutableArray<LocalSymbol>.Empty, // note that if the parameter type conflicts with the default value from attributes, // we will just get a bad constant value above and return early. new BoundLiteral(parameterSyntax, defaultValue, Type)); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Debug.Assert(diagnostics.DiagnosticBag != null); NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, parameterSyntax, diagnostics.DiagnosticBag); AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); } // This method *must not* depend on attributes on the parameter symbol. // Otherwise we will have cycles when binding usage of attributes whose constructors have optional parameters private ConstantValue MakeDefaultExpression(BindingDiagnosticBag diagnostics, out Binder? binder, out BoundParameterEqualsValue? parameterEqualsValue) { binder = null; parameterEqualsValue = null; var parameterSyntax = this.CSharpSyntaxNode; if (parameterSyntax == null) { return ConstantValue.NotAvailable; } var defaultSyntax = parameterSyntax.Default; if (defaultSyntax == null) { return ConstantValue.NotAvailable; } binder = GetBinder(defaultSyntax); Binder binderForDefault = binder.CreateBinderForParameterDefaultValue(this, defaultSyntax); Debug.Assert(binderForDefault.InParameterDefaultValue); Debug.Assert(binderForDefault.ContainingMemberOrLambda == ContainingSymbol); parameterEqualsValue = binderForDefault.BindParameterDefaultValue(defaultSyntax, this, diagnostics, out var valueBeforeConversion); if (valueBeforeConversion.HasErrors) { return ConstantValue.Bad; } BoundExpression convertedExpression = parameterEqualsValue.Value; bool hasErrors = ParameterHelpers.ReportDefaultParameterErrors(binder, ContainingSymbol, parameterSyntax, this, valueBeforeConversion, convertedExpression, diagnostics); if (hasErrors) { return ConstantValue.Bad; } // If we have something like M(double? x = 1) then the expression we'll get is (double?)1, which // does not have a constant value. The constant value we want is (double)1. // The default literal conversion is an exception: (double)default would give the wrong value for M(double? x = default). if (convertedExpression.ConstantValue == null && convertedExpression.Kind == BoundKind.Conversion && ((BoundConversion)convertedExpression).ConversionKind != ConversionKind.DefaultLiteral) { if (parameterType.Type.IsNullableType()) { convertedExpression = binder.GenerateConversionForAssignment(parameterType.Type.GetNullableUnderlyingType(), valueBeforeConversion, diagnostics, isDefaultParameter: true); } } // represent default(struct) by a Null constant: var value = convertedExpression.ConstantValue ?? ConstantValue.Null; return value; } #nullable disable public override string MetadataName { get { // The metadata parameter name should be the name used in the partial definition. var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return base.MetadataName; } var definition = sourceMethod.SourcePartialDefinition; if ((object)definition == null) { return base.MetadataName; } return definition.Parameters[this.Ordinal].MetadataName; } } protected virtual IAttributeTargetSymbol AttributeOwner => this; IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner; AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Parameter; AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { if (SynthesizedRecordPropertySymbol.HaveCorrespondingSynthesizedRecordPropertySymbol(this)) { return AttributeLocation.Parameter | AttributeLocation.Property | AttributeLocation.Field; } return AttributeLocation.Parameter; } } /// <summary> /// Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source parameter symbols. /// </summary> /// <remarks> /// Used for parameters of partial implementation. We bind the attributes only on the definition /// part and copy them over to the implementation. /// </remarks> private SourceParameterSymbol BoundAttributesSource { get { var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return null; } var impl = sourceMethod.SourcePartialImplementation; if ((object)impl == null) { return null; } return (SourceParameterSymbol)impl.Parameters[this.Ordinal]; } } internal sealed override SyntaxList<AttributeListSyntax> AttributeDeclarationList { get { var syntax = this.CSharpSyntaxNode; return (syntax != null) ? syntax.AttributeLists : default(SyntaxList<AttributeListSyntax>); } } /// <summary> /// Gets the syntax list of custom attributes that declares attributes for this parameter symbol. /// </summary> internal virtual OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // C# spec: // The attributes on the parameters of the resulting method declaration // are the combined attributes of the corresponding parameters of the defining // and the implementing partial method declaration in unspecified order. // Duplicates are not removed. SyntaxList<AttributeListSyntax> attributes = AttributeDeclarationList; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null) { return OneOrMany.Create(attributes); } SyntaxList<AttributeListSyntax> otherAttributes; // if this is a definition get the implementation and vice versa SourceOrdinaryMethodSymbol otherPart = sourceMethod.OtherPartOfPartial; if ((object)otherPart != null) { otherAttributes = ((SourceParameterSymbol)otherPart.Parameters[this.Ordinal]).AttributeDeclarationList; } else { otherAttributes = default(SyntaxList<AttributeListSyntax>); } if (attributes.Equals(default(SyntaxList<AttributeListSyntax>))) { return OneOrMany.Create(otherAttributes); } else if (otherAttributes.Equals(default(SyntaxList<AttributeListSyntax>))) { return OneOrMany.Create(attributes); } return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)); } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal ParameterWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ParameterWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } /// <summary> /// Returns data decoded from special 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> internal ParameterEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ParameterEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal sealed override CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { SourceParameterSymbol copyFrom = this.BoundAttributesSource; // prevent infinite recursion: Debug.Assert(!ReferenceEquals(copyFrom, this)); bool bagCreatedOnThisThread; if ((object)copyFrom != null) { var attributesBag = copyFrom.GetAttributesBag(); bagCreatedOnThisThread = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } else { var attributeSyntax = this.GetAttributeDeclarations(); bagCreatedOnThisThread = LoadAndValidateAttributes(attributeSyntax, ref _lazyCustomAttributesBag, binderOpt: ParameterBinderOpt); } if (bagCreatedOnThisThread) { NullableAnalyzeParameterDefaultValueFromAttributes(); state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EarlyDecodeWellKnownAttributeType(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax) { Debug.Assert(!attributeType.IsErrorType()); // NOTE: OptionalAttribute is decoded specially before any of the other attributes and stored in the parameter // symbol (rather than in the EarlyWellKnownAttributeData) because it is needed during overload resolution. if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.OptionalAttribute)) { _lazyHasOptionalAttribute = ThreeState.True; } } internal override void PostEarlyDecodeWellKnownAttributeTypes() { if (_lazyHasOptionalAttribute == ThreeState.Unknown) { _lazyHasOptionalAttribute = ThreeState.False; } base.PostEarlyDecodeWellKnownAttributeTypes(); } internal override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, ref arguments); } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, ref arguments); } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute)) { return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, ref arguments); } else if (!IsOnPartialImplementation(arguments.AttributeSyntax)) { if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerLineNumberAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerFilePathAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute)) { arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerMemberNameAttribute = true; } else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute)) { var index = -1; var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out _); if (!attribute.HasErrors) { var constructorArguments = attribute.CommonConstructorArguments; Debug.Assert(constructorArguments.Length == 1); if (constructorArguments[0].TryDecodeValue(SpecialType.System_String, out string parameterName)) { var parameters = ContainingSymbol.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].Name.Equals(parameterName, StringComparison.Ordinal)) { index = i; break; } } } } arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().CallerArgumentExpressionParameterIndex = index; } } return base.EarlyDecodeWellKnownAttribute(ref arguments); } private CSharpAttributeData EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription description, ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) || description.Equals(AttributeDescription.DecimalConstantAttribute) || description.Equals(AttributeDescription.DateTimeConstantAttribute)); bool hasAnyDiagnostics; var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); ConstantValue value; if (attribute.HasErrors) { value = ConstantValue.Bad; hasAnyDiagnostics = true; } else { value = DecodeDefaultParameterValueAttribute(description, attribute, arguments.AttributeSyntax, diagnose: false, diagnosticsOpt: null); } var paramData = arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>(); if (paramData.DefaultParameterValue == ConstantValue.Unset) { paramData.DefaultParameterValue = value; } return !hasAnyDiagnostics ? attribute : null; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); Debug.Assert(AttributeDescription.InterpolatedStringHandlerArgumentAttribute.Signatures.Length == 2); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultParameterValueAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute)) { // Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.OptionalAttribute)) { Debug.Assert(_lazyHasOptionalAttribute == ThreeState.True); if (HasDefaultArgumentSyntax) { // error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute diagnostics.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, arguments.AttributeSyntaxOpt.Name.Location); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.ParamArrayAttribute)) { // error CS0674: Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead. diagnostics.Add(ErrorCode.ERR_ExplicitParamArray, arguments.AttributeSyntaxOpt.Name.Location); } else if (attribute.IsTargetAttribute(this, AttributeDescription.InAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasInAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.OutAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasOutAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute)) { MarshalAsAttributeDecoder<ParameterWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>.Decode(ref arguments, AttributeTargets.Parameter, MessageProvider.Instance); } else if (attribute.IsTargetAttribute(this, AttributeDescription.IDispatchConstantAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIDispatchConstantAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.IUnknownConstantAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIUnknownConstantAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerLineNumberAttribute)) { ValidateCallerLineNumberAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerFilePathAttribute)) { ValidateCallerFilePathAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerMemberNameAttribute)) { ValidateCallerMemberNameAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerArgumentExpressionAttribute)) { ValidateCallerArgumentExpressionAttribute(arguments.AttributeSyntaxOpt, attribute, diagnostics); } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasAllowNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasDisallowNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasMaybeNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullWhenAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().MaybeNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.MaybeNullWhenAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasNotNullAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullWhenAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().NotNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.NotNullWhenAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DoesNotReturnIfAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().DoesNotReturnIfAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.DoesNotReturnIfAttribute, attribute); } else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullIfNotNullAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().AddNotNullIfParameterNotNull(attribute.DecodeNotNullIfNotNullAttribute()); } else if (attribute.IsTargetAttribute(this, AttributeDescription.EnumeratorCancellationAttribute)) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasEnumeratorCancellationAttribute = true; ValidateCancellationTokenAttribute(arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); } else if (attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.InterpolatedStringHandlerArgumentAttribute) is (0 or 1) and var index) { DecodeInterpolatedStringHandlerArgumentAttribute(ref arguments, diagnostics, index); } } private static bool? DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription description, CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_Boolean, out bool value) ? (bool?)value : null; } private void DecodeDefaultParameterValueAttribute(AttributeDescription description, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { var attribute = arguments.Attribute; var syntax = arguments.AttributeSyntaxOpt; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); var value = DecodeDefaultParameterValueAttribute(description, attribute, syntax, diagnose: true, diagnosticsOpt: diagnostics); if (!value.IsBad) { VerifyParamDefaultValueMatchesAttributeIfAny(value, syntax, diagnostics); } } /// <summary> /// Verify the default value matches the default value from any earlier attribute /// (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). /// If not, report ERR_ParamDefaultValueDiffersFromAttribute. /// </summary> private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { var data = GetEarlyDecodedWellKnownAttributeData(); if (data != null) { var attrValue = data.DefaultParameterValue; if ((attrValue != ConstantValue.Unset) && (value != attrValue)) { // CS8017: The parameter has multiple distinct default values. diagnostics.Add(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, syntax.Location); } } } private ConstantValue DecodeDefaultParameterValueAttribute(AttributeDescription description, CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) { Debug.Assert(!attribute.HasErrors); if (description.Equals(AttributeDescription.DefaultParameterValueAttribute)) { return DecodeDefaultParameterValueAttribute(attribute, node, diagnose, diagnosticsOpt); } else if (description.Equals(AttributeDescription.DecimalConstantAttribute)) { return attribute.DecodeDecimalConstantValue(); } else { Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute)); return attribute.DecodeDateTimeConstantValue(); } } private ConstantValue DecodeDefaultParameterValueAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) { Debug.Assert(!diagnose || diagnosticsOpt != null); if (HasDefaultArgumentSyntax) { // error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, node.Name.Location); } return ConstantValue.Bad; } // BREAK: In dev10, DefaultParameterValueAttribute could not be applied to System.Type or array parameters. // When this was attempted, dev10 produced CS1909, ERR_DefaultValueBadParamType. Roslyn takes a different // approach: instead of looking at the parameter type, we look at the argument type. There's nothing wrong // with providing a default value for a System.Type or array parameter, as long as the default parameter // is not a System.Type or an array (i.e. null is fine). Since we are no longer interested in the type of // the parameter, all occurrences of CS1909 have been replaced with CS1910, ERR_DefaultValueBadValueType, // to indicate that the argument type, rather than the parameter type, is the source of the problem. Debug.Assert(attribute.CommonConstructorArguments.Length == 1); // the type of the value is the type of the expression in the attribute: var arg = attribute.CommonConstructorArguments[0]; SpecialType specialType = arg.Kind == TypedConstantKind.Enum ? ((NamedTypeSymbol)arg.TypeInternal).EnumUnderlyingType.SpecialType : arg.TypeInternal.SpecialType; var compilation = this.DeclaringCompilation; var constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnosticsOpt, ContainingAssembly); if (constantValueDiscriminator == ConstantValueTypeDiscriminator.Bad) { if (arg.Kind != TypedConstantKind.Array && arg.ValueInternal == null) { if (this.Type.IsReferenceType) { constantValueDiscriminator = ConstantValueTypeDiscriminator.Null; } else { // error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location); } return ConstantValue.Bad; } } else { // error CS1910: Argument of type '{0}' is not applicable for the DefaultParameterValue attribute if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueBadValueType, node.Name.Location, arg.TypeInternal); } return ConstantValue.Bad; } } else if (!compilation.Conversions.ClassifyConversionFromType((TypeSymbol)arg.TypeInternal, this.Type, ref useSiteInfo).Kind.IsImplicitConversion()) { // error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location); diagnosticsOpt.Add(node.Name.Location, useSiteInfo); } return ConstantValue.Bad; } if (diagnose) { diagnosticsOpt.Add(node.Name.Location, useSiteInfo); } return ConstantValue.Create(arg.ValueInternal, constantValueDiscriminator); } private bool IsValidCallerInfoContext(AttributeSyntax node) => !ContainingSymbol.IsExplicitInterfaceImplementation() && !ContainingSymbol.IsOperator() && !IsOnPartialImplementation(node); /// <summary> /// Is the attribute syntax appearing on a parameter of a partial method implementation part? /// Since attributes are merged between the parts of a partial, we need to look at the syntax where the /// attribute appeared in the source to see if it corresponds to a partial method implementation part. /// </summary> /// <param name="node"></param> /// <returns></returns> private bool IsOnPartialImplementation(AttributeSyntax node) { var method = ContainingSymbol as MethodSymbol; if ((object)method == null) return false; var impl = method.IsPartialImplementation() ? method : method.PartialImplementationPart; if ((object)impl == null) return false; var paramList = node // AttributeSyntax .Parent // AttributeListSyntax .Parent // ParameterSyntax .Parent as ParameterListSyntax; // ParameterListSyntax if (paramList == null) return false; var methDecl = paramList.Parent as MethodDeclarationSyntax; if (methDecl == null) return false; foreach (var r in impl.DeclaringSyntaxReferences) { if (r.GetSyntax() == methDecl) return true; } return false; } private void ValidateCallerLineNumberAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4024: The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerLineNumberConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol intType = compilation.GetSpecialType(SpecialType.System_Int32); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerLineNumberParam, node.Name.Location, intType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4020: The CallerLineNumberAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerLineNumberParamWithoutDefaultValue, node.Name.Location); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerFilePathAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4025: The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4018: CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerFilePathParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4021: The CallerFilePathAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerFilePathParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS7082: The CallerFilePathAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerMemberNameAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS4026: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerMemberNameParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS4022: The CallerMemberNameAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerMemberNameParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS7081: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerFilePath) { // CS7080: The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCallerArgumentExpressionAttribute(AttributeSyntax node, CSharpAttributeData attribute, BindingDiagnosticBag diagnostics) { // We intentionally don't report an error for earlier language versions here. The attribute already existed // before the feature was developed. The error is only reported when the binder supplies a value // based on the attribute. CSharpCompilation compilation = this.DeclaringCompilation; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!IsValidCallerInfoContext(node)) { // CS8966: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) { // CS8959: CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String); diagnostics.Add(ErrorCode.ERR_NoConversionForCallerArgumentExpressionParam, node.Name.Location, stringType, TypeWithAnnotations.Type); } else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default { // Unconsumed location checks happen first, so we require a default value. // CS8964: The CallerArgumentExpressionAttribute may only be applied to parameters with default values diagnostics.Add(ErrorCode.ERR_BadCallerArgumentExpressionParamWithoutDefaultValue, node.Name.Location); } else if (IsCallerLineNumber) { // CS8960: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerFilePath) { // CS8961: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (IsCallerMemberName) { // CS8962: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute. diagnostics.Add(ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (attribute.CommonConstructorArguments.Length == 1 && GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex == -1) { // CS8963: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name. diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } else if (GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex == Ordinal) { // CS8965: The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential. diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } diagnostics.Add(node.Name.Location, useSiteInfo); } private void ValidateCancellationTokenAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { if (needsReporting()) { diagnostics.Add(ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText); } bool needsReporting() { if (!Type.Equals(this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Threading_CancellationToken))) { return true; } else if (this.ContainingSymbol is MethodSymbol method && method.IsAsync && method.ReturnType.OriginalDefinition.Equals(this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T))) { // Note: async methods that return this type must be iterators. This is enforced elsewhere return false; } return true; } } #nullable enable private void DecodeInterpolatedStringHandlerArgumentAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, BindingDiagnosticBag diagnostics, int attributeIndex) { Debug.Assert(attributeIndex is 0 or 1); Debug.Assert(arguments.Attribute.IsTargetAttribute(this, AttributeDescription.InterpolatedStringHandlerArgumentAttribute) && arguments.Attribute.CommonConstructorArguments.Length == 1); Debug.Assert(arguments.AttributeSyntaxOpt is not null); var errorLocation = arguments.AttributeSyntaxOpt.Location; if (Type is not NamedTypeSymbol { IsInterpolatedStringHandlerType: true } handlerType) { // '{0}' is not an interpolated string handler type. diagnostics.Add(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, errorLocation, Type); setInterpolatedStringHandlerAttributeError(ref arguments); return; } TypedConstant constructorArgument = arguments.Attribute.CommonConstructorArguments[0]; ImmutableArray<ParameterSymbol> containingSymbolParameters = ContainingSymbol.GetParameters(); ImmutableArray<int> parameterOrdinals; ArrayBuilder<ParameterSymbol?> parameters; if (attributeIndex == 0) { if (decodeName(constructorArgument, ref arguments) is not (int ordinal, var parameter)) { // If an error needs to be reported, it will already have been reported by another step. setInterpolatedStringHandlerAttributeError(ref arguments); return; } parameterOrdinals = ImmutableArray.Create(ordinal); parameters = ArrayBuilder<ParameterSymbol?>.GetInstance(1); parameters.Add(parameter); } else if (attributeIndex == 1) { bool hadError = false; parameters = ArrayBuilder<ParameterSymbol?>.GetInstance(constructorArgument.Values.Length); var ordinalsBuilder = ArrayBuilder<int>.GetInstance(constructorArgument.Values.Length); foreach (var nestedArgument in constructorArgument.Values) { if (decodeName(nestedArgument, ref arguments) is (int ordinal, var parameter) && !hadError) { parameters.Add(parameter); ordinalsBuilder.Add(ordinal); } else { hadError = true; } } if (hadError) { parameters.Free(); ordinalsBuilder.Free(); setInterpolatedStringHandlerAttributeError(ref arguments); return; } parameterOrdinals = ordinalsBuilder.ToImmutableAndFree(); } else { throw ExceptionUtilities.Unreachable; } var parameterWellKnownAttributeData = arguments.GetOrCreateData<ParameterWellKnownAttributeData>(); parameterWellKnownAttributeData.InterpolatedStringHandlerArguments = parameterOrdinals; (int Ordinal, ParameterSymbol? Parameter)? decodeName(TypedConstant constant, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert(arguments.AttributeSyntaxOpt is not null); if (constant.IsNull) { // null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. diagnostics.Add(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location); return null; } if (constant.TypeInternal is not { SpecialType: SpecialType.System_String }) { // There has already been an error reported. Just return null. return null; } var name = constant.DecodeValue<string>(SpecialType.System_String); Debug.Assert(name != null); if (name == "") { // Name refers to the "this" instance parameter. if (!ContainingSymbol.RequiresInstanceReceiver() || ContainingSymbol is MethodSymbol { MethodKind: MethodKind.Constructor }) { // '{0}' is not an instance method, the receiver cannot be an interpolated string handler argument. diagnostics.Add(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location, ContainingSymbol); return null; } return (BoundInterpolatedStringArgumentPlaceholder.InstanceParameter, null); } var parameter = containingSymbolParameters.FirstOrDefault(static (param, name) => string.Equals(param.Name, name, StringComparison.Ordinal), name); if (parameter is null) { // '{0}' is not a valid parameter name from '{1}'. diagnostics.Add(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, arguments.AttributeSyntaxOpt.Location, name, ContainingSymbol); return null; } if ((object)parameter == this) { // InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. diagnostics.Add(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, errorLocation); return null; } if (parameter.Ordinal > Ordinal) { // Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. // This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated // string handler parameter after all arguments involved. diagnostics.Add(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, errorLocation, parameter.Name, this); } return (parameter.Ordinal, parameter); } static void setInterpolatedStringHandlerAttributeError(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { arguments.GetOrCreateData<ParameterWellKnownAttributeData>().InterpolatedStringHandlerArguments = default; } } #nullable disable internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) { Debug.Assert(!boundAttributes.IsDefault); Debug.Assert(!allAttributeSyntaxNodes.IsDefault); Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length); Debug.Assert(_lazyCustomAttributesBag != null); Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed); Debug.Assert(symbolPart == AttributeLocation.None); var data = (ParameterWellKnownAttributeData)decodedData; if (data != null) { switch (RefKind) { case RefKind.Ref: if (data.HasOutAttribute && !data.HasInAttribute) { // error CS0662: Cannot specify the Out attribute on a ref parameter without also specifying the In attribute. diagnostics.Add(ErrorCode.ERR_OutAttrOnRefParam, this.Locations[0]); } break; case RefKind.Out: if (data.HasInAttribute) { // error CS0036: An out parameter cannot have the In attribute. diagnostics.Add(ErrorCode.ERR_InAttrOnOutParam, this.Locations[0]); } break; case RefKind.In: if (data.HasOutAttribute) { // error CS8355: An in parameter cannot have the Out attribute. diagnostics.Add(ErrorCode.ERR_OutAttrOnInParam, this.Locations[0]); } break; } } base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); } /// <summary> /// True if the parameter has default argument syntax. /// </summary> internal override bool HasDefaultArgumentSyntax { get { return (_parameterSyntaxKind & ParameterSyntaxKind.DefaultParameter) != 0; } } /// <summary> /// True if the parameter is marked by <see cref="System.Runtime.InteropServices.OptionalAttribute"/>. /// </summary> internal sealed override bool HasOptionalAttribute { get { if (_lazyHasOptionalAttribute == ThreeState.Unknown) { SourceParameterSymbol copyFrom = this.BoundAttributesSource; // prevent infinite recursion: Debug.Assert(!ReferenceEquals(copyFrom, this)); if ((object)copyFrom != null) { // Parameter of partial implementation. // We bind the attributes only on the definition part and copy them over to the implementation. _lazyHasOptionalAttribute = copyFrom.HasOptionalAttribute.ToThreeState(); } else { // lazyHasOptionalAttribute is decoded early, hence we cannot reach here when binding attributes for this symbol. // So it is fine to force complete attributes here. var attributes = GetAttributes(); if (!attributes.Any()) { _lazyHasOptionalAttribute = ThreeState.False; } } } Debug.Assert(_lazyHasOptionalAttribute.HasValue()); return _lazyHasOptionalAttribute.Value(); } } internal override bool IsMetadataOptional { get { // NOTE: IsMetadataOptional property can be invoked during overload resolution. // NOTE: Optional attribute is decoded very early in attribute binding phase, see method EarlyDecodeOptionalAttribute // NOTE: If you update the below check to look for any more attributes, make sure that they are decoded early. return HasDefaultArgumentSyntax || HasOptionalAttribute; } } internal sealed override bool IsMetadataIn => base.IsMetadataIn || GetDecodedWellKnownAttributeData()?.HasInAttribute == true; internal sealed override bool IsMetadataOut => base.IsMetadataOut || GetDecodedWellKnownAttributeData()?.HasOutAttribute == true; internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation => GetDecodedWellKnownAttributeData()?.MarshallingInformation; public override bool IsParams => (_parameterSyntaxKind & ParameterSyntaxKind.ParamsParameter) != 0; internal override bool IsExtensionMethodThis => (_parameterSyntaxKind & ParameterSyntaxKind.ExtensionThisParameter) != 0; public override ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { _ = this.GetAttributes(); _ = this.ExplicitDefaultConstantValue; state.SpinWaitComplete(CompletionPart.ComplexParameterSymbolAll, cancellationToken); } } internal sealed class SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef : SourceComplexParameterSymbol { private readonly ImmutableArray<CustomModifier> _refCustomModifiers; internal SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, string name, ImmutableArray<Location> locations, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis) : base(owner, ordinal, parameterType, refKind, name, locations, syntaxRef, isParams, isExtensionMethodThis) { Debug.Assert(!refCustomModifiers.IsEmpty); _refCustomModifiers = refCustomModifiers; Debug.Assert(refKind != RefKind.None || _refCustomModifiers.IsEmpty); } public override ImmutableArray<CustomModifier> RefCustomModifiers => _refCustomModifiers; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorCases { internal class ExceptionInCodeAction : CodeRefactoringProvider { public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(new ExceptionCodeAction(), context.Span); return Task.CompletedTask; } internal class ExceptionCodeAction : CodeAction { public override string Title { get { throw new Exception($"Exception thrown from get_Title in {nameof(ExceptionCodeAction)}"); } } public override string EquivalenceKey { get { throw new Exception($"Exception thrown from get_EquivalenceKey in {nameof(ExceptionCodeAction)}"); } } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from ComputePreviewOperationsAsync in {nameof(ExceptionCodeAction)}"); protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from ComputeOperationsAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from GetChangedDocumentAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from GetChangedSolutionAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) => throw new Exception($"Exception thrown from PostProcessChangesAsync in {nameof(ExceptionCodeAction)}"); public override int GetHashCode() => throw new Exception($"Exception thrown from GetHashCode in {nameof(ExceptionCodeAction)}"); public override bool Equals(object obj) => throw new Exception($"Exception thrown from Equals in {nameof(ExceptionCodeAction)}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorCases { internal class ExceptionInCodeAction : CodeRefactoringProvider { public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(new ExceptionCodeAction(), context.Span); return Task.CompletedTask; } internal class ExceptionCodeAction : CodeAction { public override string Title { get { throw new Exception($"Exception thrown from get_Title in {nameof(ExceptionCodeAction)}"); } } public override string EquivalenceKey { get { throw new Exception($"Exception thrown from get_EquivalenceKey in {nameof(ExceptionCodeAction)}"); } } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from ComputePreviewOperationsAsync in {nameof(ExceptionCodeAction)}"); protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from ComputeOperationsAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from GetChangedDocumentAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) => throw new Exception($"Exception thrown from GetChangedSolutionAsync in {nameof(ExceptionCodeAction)}"); protected override Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) => throw new Exception($"Exception thrown from PostProcessChangesAsync in {nameof(ExceptionCodeAction)}"); public override int GetHashCode() => throw new Exception($"Exception thrown from GetHashCode in {nameof(ExceptionCodeAction)}"); public override bool Equals(object obj) => throw new Exception($"Exception thrown from Equals in {nameof(ExceptionCodeAction)}"); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Preview/ChangeList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList { public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>()); internal AbstractChange[] Changes { get; } public ChangeList(AbstractChange[] changes) => this.Changes = changes; public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData) { pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE; // Set TDS_SELECTED and TDS_GRAYTEXT pData[0].State = Changes[index].GetDisplayState(); Changes[index].GetDisplayData(pData); return VSConstants.S_OK; } public int GetExpandable(uint index, out int pfExpandable) { pfExpandable = Changes[index].IsExpandable; return VSConstants.S_OK; } public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode) { pfCanRecurse = Changes[index].CanRecurse; pptlNode = (IVsLiteTreeList)Changes[index].GetChildren(); return VSConstants.S_OK; } public int GetFlags(out uint pFlags) { // The interface IVsSimplePreviewChangesList doesn't include this method. // Setting flags to 0 is necessary to make the underlying treeview draw // checkboxes and make them clickable. pFlags = 0; return VSConstants.S_OK; } public int GetItemCount(out uint pCount) { pCount = (uint)Changes.Length; return VSConstants.S_OK; } public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges) => VSConstants.E_FAIL; public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText) => Changes[index].GetText(out _, out ppszText); public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText) => Changes[index].GetTipText(out _, out ppszText); public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex) { for (var i = 0; i < Changes.Length; i++) { if (Changes[i].GetChildren() == child) { iIndex = (uint)i; return VSConstants.S_OK; } } iIndex = 0; return VSConstants.S_FALSE; } public int OnClose(VSTREECLOSEACTIONS[] ptca) => VSConstants.S_OK; public int OnRequestSource(uint index, object pIUnknownTextView) => Changes[index].OnRequestSource(pIUnknownTextView); public int ToggleState(uint index, out uint ptscr) { Changes[index].Toggle(); ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE; Changes[index].OnRequestSource(null); return VSConstants.S_OK; } public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges) { pCurUpdate = 0; pgrfChanges = 0; 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; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList { public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>()); internal AbstractChange[] Changes { get; } public ChangeList(AbstractChange[] changes) => this.Changes = changes; public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData) { pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE; // Set TDS_SELECTED and TDS_GRAYTEXT pData[0].State = Changes[index].GetDisplayState(); Changes[index].GetDisplayData(pData); return VSConstants.S_OK; } public int GetExpandable(uint index, out int pfExpandable) { pfExpandable = Changes[index].IsExpandable; return VSConstants.S_OK; } public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode) { pfCanRecurse = Changes[index].CanRecurse; pptlNode = (IVsLiteTreeList)Changes[index].GetChildren(); return VSConstants.S_OK; } public int GetFlags(out uint pFlags) { // The interface IVsSimplePreviewChangesList doesn't include this method. // Setting flags to 0 is necessary to make the underlying treeview draw // checkboxes and make them clickable. pFlags = 0; return VSConstants.S_OK; } public int GetItemCount(out uint pCount) { pCount = (uint)Changes.Length; return VSConstants.S_OK; } public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges) => VSConstants.E_FAIL; public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText) => Changes[index].GetText(out _, out ppszText); public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText) => Changes[index].GetTipText(out _, out ppszText); public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex) { for (var i = 0; i < Changes.Length; i++) { if (Changes[i].GetChildren() == child) { iIndex = (uint)i; return VSConstants.S_OK; } } iIndex = 0; return VSConstants.S_FALSE; } public int OnClose(VSTREECLOSEACTIONS[] ptca) => VSConstants.S_OK; public int OnRequestSource(uint index, object pIUnknownTextView) => Changes[index].OnRequestSource(pIUnknownTextView); public int ToggleState(uint index, out uint ptscr) { Changes[index].Toggle(); ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE; Changes[index].OnRequestSource(null); return VSConstants.S_OK; } public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges) { pCurUpdate = 0; pgrfChanges = 0; return VSConstants.S_OK; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.Tree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ClosureConversion { internal sealed partial class Analysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// This is the core node for a Scope tree, which stores all semantically meaningful /// information about declared variables, closures, and environments in each scope. /// It can be thought of as the essence of the bound tree -- stripping away many of /// the unnecessary details stored in the bound tree and just leaving the pieces that /// are important for closure conversion. The root scope is the method scope for the /// method being analyzed and has a null <see cref="Parent" />. /// </summary> [DebuggerDisplay("{ToString(), nq}")] public sealed class Scope { public readonly Scope Parent; public readonly ArrayBuilder<Scope> NestedScopes = ArrayBuilder<Scope>.GetInstance(); /// <summary> /// A list of all nested functions (all lambdas and local functions) declared in this scope. /// </summary> public readonly ArrayBuilder<NestedFunction> NestedFunctions = ArrayBuilder<NestedFunction>.GetInstance(); /// <summary> /// A list of all locals or parameters that were declared in this scope and captured /// in this scope or nested scopes. "Declared" refers to the start of the variable /// lifetime (which, at this point in lowering, should be equivalent to lexical scope). /// </summary> /// <remarks> /// It's important that this is a set and that enumeration order is deterministic. We loop /// over this list to generate proxies and if we loop out of order this will cause /// non-deterministic compilation, and if we generate duplicate proxies we'll generate /// wasteful code in the best case and incorrect code in the worst. /// </remarks> public readonly SetWithInsertionOrder<Symbol> DeclaredVariables = new SetWithInsertionOrder<Symbol>(); /// <summary> /// The bound node representing this scope. This roughly corresponds to the bound /// node for the block declaring locals for this scope, although parameters of /// methods/functions are introduced into their Body's scope and do not get their /// own scope. /// </summary> public readonly BoundNode BoundNode; /// <summary> /// The nested function that this scope is nested inside. Null if this scope is not nested /// inside a nested function. /// </summary> public readonly NestedFunction ContainingFunctionOpt; #nullable enable /// <summary> /// Environment created in this scope to hold <see cref="DeclaredVariables"/>. /// At the moment, all variables declared in the same scope /// always get assigned to the same environment. /// </summary> public ClosureEnvironment? DeclaredEnvironment = null; #nullable disable public Scope(Scope parent, BoundNode boundNode, NestedFunction containingFunction) { Debug.Assert(boundNode != null); Parent = parent; BoundNode = boundNode; ContainingFunctionOpt = containingFunction; } /// <summary> /// Is it safe to move any of the variables declared in this scope to the parent scope, /// or would doing so change the meaning of the program? /// </summary> public bool CanMergeWithParent { get; internal set; } = true; public void Free() { foreach (var scope in NestedScopes) { scope.Free(); } NestedScopes.Free(); foreach (var function in NestedFunctions) { function.Free(); } NestedFunctions.Free(); } public override string ToString() => BoundNode.Syntax.GetText().ToString(); } /// <summary> /// The NestedFunction type represents a lambda or local function and stores /// information related to that function. After initially building the /// <see cref="Scope"/> tree the only information available is /// <see cref="OriginalMethodSymbol"/> and <see cref="CapturedVariables"/>. /// Subsequent passes are responsible for translating captured /// variables into captured environments and for calculating /// the rewritten signature of the method. /// </summary> public sealed class NestedFunction { /// <summary> /// The method symbol for the original lambda or local function. /// </summary> public readonly MethodSymbol OriginalMethodSymbol; /// <summary> /// Syntax for the block of the nested function. /// </summary> public readonly SyntaxReference BlockSyntax; public readonly PooledHashSet<Symbol> CapturedVariables = PooledHashSet<Symbol>.GetInstance(); public readonly ArrayBuilder<ClosureEnvironment> CapturedEnvironments = ArrayBuilder<ClosureEnvironment>.GetInstance(); public ClosureEnvironment ContainingEnvironmentOpt; private bool _capturesThis; /// <summary> /// True if this function directly or transitively captures 'this' (captures /// a local function which directly or indirectly captures 'this'). /// Calculated in <see cref="MakeAndAssignEnvironments"/>. /// </summary> public bool CapturesThis { get => _capturesThis; set { Debug.Assert(value); _capturesThis = value; } } public SynthesizedClosureMethod SynthesizedLoweredMethod; public NestedFunction(MethodSymbol symbol, SyntaxReference blockSyntax) { Debug.Assert(symbol != null); OriginalMethodSymbol = symbol; BlockSyntax = blockSyntax; } public void Free() { CapturedVariables.Free(); CapturedEnvironments.Free(); } } public sealed class ClosureEnvironment { public readonly SetWithInsertionOrder<Symbol> CapturedVariables; /// <summary> /// True if this environment captures a reference to a class environment /// declared in a higher scope. Assigned by /// <see cref="ComputeLambdaScopesAndFrameCaptures()"/> /// </summary> public bool CapturesParent; public readonly bool IsStruct; internal SynthesizedClosureEnvironment SynthesizedEnvironment; public ClosureEnvironment(IEnumerable<Symbol> capturedVariables, bool isStruct) { CapturedVariables = new SetWithInsertionOrder<Symbol>(); foreach (var item in capturedVariables) { CapturedVariables.Add(item); } IsStruct = isStruct; } } /// <summary> /// Visit all nested functions in all nested scopes and run the <paramref name="action"/>. /// </summary> public static void VisitNestedFunctions(Scope scope, Action<Scope, NestedFunction> action) { foreach (var function in scope.NestedFunctions) { action(scope, function); } foreach (var nested in scope.NestedScopes) { VisitNestedFunctions(nested, action); } } /// <summary> /// Visit all the functions and return true when the <paramref name="func"/> returns /// true. Otherwise, returns false. /// </summary> public static bool CheckNestedFunctions(Scope scope, Func<Scope, NestedFunction, bool> func) { foreach (var function in scope.NestedFunctions) { if (func(scope, function)) { return true; } } foreach (var nested in scope.NestedScopes) { if (CheckNestedFunctions(nested, func)) { return true; } } return false; } /// <summary> /// Visit the tree with the given root and run the <paramref name="action"/> /// </summary> public static void VisitScopeTree(Scope treeRoot, Action<Scope> action) { action(treeRoot); foreach (var nested in treeRoot.NestedScopes) { VisitScopeTree(nested, action); } } /// <summary> /// Builds a tree of <see cref="Scope"/> nodes corresponding to a given method. /// <see cref="Build(BoundNode, MethodSymbol, HashSet{MethodSymbol}, DiagnosticBag)"/> /// visits the bound tree and translates information from the bound tree about /// variable scope, declared variables, and variable captures into the resulting /// <see cref="Scope"/> tree. /// /// At the same time it sets <see cref="Scope.CanMergeWithParent"/> /// for each Scope. This is done by looking for <see cref="BoundGotoStatement"/>s /// and <see cref="BoundConditionalGoto"/>s that jump from a point /// after the beginning of a <see cref="Scope"/>, to a <see cref="BoundLabelStatement"/> /// before the start of the scope, but after the start of <see cref="Scope.Parent"/>. /// /// All loops have been converted to gotos and labels by this stage, /// so we do not have to visit them to do so. Similarly all <see cref="BoundLabeledStatement"/>s /// have been converted to <see cref="BoundLabelStatement"/>s, so we do not have to /// visit them. /// </summary> private class ScopeTreeBuilder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Do not set this directly, except when setting the root scope. /// Instead use <see cref="PopScope"/> or <see cref="CreateAndPushScope"/>. /// </summary> private Scope _currentScope; /// <summary> /// Null if we're not inside a nested function, otherwise the nearest nested function. /// </summary> private NestedFunction _currentFunction = null; private bool _inExpressionTree = false; /// <summary> /// A mapping from all captured vars to the scope they were declared in. This /// is used when recording captured variables as we must know what the lifetime /// of a captured variable is to determine the lifetime of its capture environment. /// </summary> private readonly SmallDictionary<Symbol, Scope> _localToScope = new SmallDictionary<Symbol, Scope>(); #if DEBUG /// <summary> /// Free variables are variables declared in expression statements that can then /// be captured in nested lambdas. Normally, captured variables must lowered as /// part of closure conversion, but expression tree variables are handled separately /// by the expression tree rewriter and are considered free for the purposes of /// closure conversion. For instance, an expression with a nested lambda, e.g. /// x => y => x + y /// contains an expression variable, x, that should not be treated as a captured /// variable to be replaced by closure conversion. Instead, it should be left for /// expression tree conversion. /// </summary> private readonly HashSet<Symbol> _freeVariables = new HashSet<Symbol>(); #endif private readonly MethodSymbol _topLevelMethod; /// <summary> /// If a local function is in the set, at some point in the code it is converted /// to a delegate and should then not be optimized to a struct closure. /// Also contains all lambdas (as they are converted to delegates implicitly). /// </summary> private readonly HashSet<MethodSymbol> _methodsConvertedToDelegates; private readonly DiagnosticBag _diagnostics; /// <summary> /// For every label visited so far, this dictionary maps to a list of all scopes either visited so far, or currently being visited, /// that are both after the label, and are on the same level of the scope tree as the label. /// </summary> private readonly PooledDictionary<LabelSymbol, ArrayBuilder<Scope>> _scopesAfterLabel = PooledDictionary<LabelSymbol, ArrayBuilder<Scope>>.GetInstance(); /// <summary> /// Contains a list of the labels visited so far for each scope. /// The outer ArrayBuilder is a stack representing the chain of scopes from the root scope to the current scope, /// and for each item on the stack, the ArrayBuilder is the list of the labels visited so far for the scope. /// /// Used by <see cref="CreateAndPushScope"/> to determine which labels a new child scope appears after. /// </summary> private readonly ArrayBuilder<ArrayBuilder<LabelSymbol>> _labelsInScope = ArrayBuilder<ArrayBuilder<LabelSymbol>>.GetInstance(); private ScopeTreeBuilder( Scope rootScope, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { Debug.Assert(rootScope != null); Debug.Assert(topLevelMethod != null); Debug.Assert(methodsConvertedToDelegates != null); Debug.Assert(diagnostics != null); _currentScope = rootScope; _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _topLevelMethod = topLevelMethod; _methodsConvertedToDelegates = methodsConvertedToDelegates; _diagnostics = diagnostics; } public static Scope Build( BoundNode node, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { // This should be the top-level node Debug.Assert(node == FindNodeToAnalyze(node)); Debug.Assert(topLevelMethod != null); var rootScope = new Scope(parent: null, boundNode: node, containingFunction: null); var builder = new ScopeTreeBuilder( rootScope, topLevelMethod, methodsConvertedToDelegates, diagnostics); builder.Build(); return rootScope; } private void Build() { // Set up the current method locals DeclareLocals(_currentScope, _topLevelMethod.Parameters); // Treat 'this' as a formal parameter of the top-level method if (_topLevelMethod.TryGetThisParameter(out var thisParam) && (object)thisParam != null) { DeclareLocals(_currentScope, ImmutableArray.Create<Symbol>(thisParam)); } Visit(_currentScope.BoundNode); // Clean Up Resources foreach (var scopes in _scopesAfterLabel.Values) { scopes.Free(); } _scopesAfterLabel.Free(); Debug.Assert(_labelsInScope.Count == 1); var labels = _labelsInScope.Pop(); labels.Free(); _labelsInScope.Free(); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) => throw ExceptionUtilities.Unreachable; public override BoundNode VisitBlock(BoundBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitCatchBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitSequence(BoundSequence node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitSequence(node); PopScope(oldScope); return result; } public override BoundNode VisitLambda(BoundLambda node) { var oldInExpressionTree = _inExpressionTree; _inExpressionTree |= node.Type.IsExpressionTree(); _methodsConvertedToDelegates.Add(node.Symbol.OriginalDefinition); var result = VisitNestedFunction(node.Symbol, node.Body); _inExpressionTree = oldInExpressionTree; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) => VisitNestedFunction(node.Symbol.OriginalDefinition, node.Body); public override BoundNode VisitCall(BoundCall node) { if (node.Method.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters AddIfCaptured(node.Method.OriginalDefinition, node.Syntax); } return base.VisitCall(node); } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters var method = node.MethodOpt.OriginalDefinition; AddIfCaptured(method, node.Syntax); _methodsConvertedToDelegates.Add(method); } return base.VisitDelegateCreationExpression(node); } public override BoundNode VisitParameter(BoundParameter node) { AddIfCaptured(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } public override BoundNode VisitLocal(BoundLocal node) { AddIfCaptured(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { AddIfCaptured(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitThisReference(BoundThisReference node) { var thisParam = _topLevelMethod.ThisParameter; if (thisParam != null) { AddIfCaptured(thisParam, node.Syntax); } else { // This can occur in a delegate creation expression because the method group // in the argument can have a "this" receiver even when "this" // is not captured because a static method is selected. But we do preserve // the method group and its receiver in the bound tree. // No need to capture "this" in such case. // TODO: Why don't we drop "this" while lowering if method is static? // Actually, considering that method group expression does not evaluate to a particular value // why do we have it in the lowered tree at all? } return base.VisitThisReference(node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { _labelsInScope.Peek().Add(node.Label); _scopesAfterLabel.Add(node.Label, ArrayBuilder<Scope>.GetInstance()); return base.VisitLabelStatement(node); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { CheckCanMergeWithParent(node.Label); return base.VisitGotoStatement(node); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { CheckCanMergeWithParent(node.Label); return base.VisitConditionalGoto(node); } /// <summary> /// This is where we calculate <see cref="Scope.CanMergeWithParent"/>. /// <see cref="Scope.CanMergeWithParent"/> is always true unless we jump from after /// the beginning of a scope, to a point in between the beginning of the parent scope, and the beginning of the scope /// </summary> /// <param name="jumpTarget"></param> private void CheckCanMergeWithParent(LabelSymbol jumpTarget) { // since forward jumps can never effect Scope.SemanticallySafeToMergeIntoParent // if we have not yet seen the jumpTarget, this is a forward jump, and can be ignored if (_scopesAfterLabel.TryGetValue(jumpTarget, out var scopesAfterLabel)) { foreach (var scope in scopesAfterLabel) { // this jump goes from a point after the beginning of the scope (as we have already visited or started visiting the scope), // to a point in between the beginning of the parent scope, and the beginning of the scope, so it is not safe to move // variables in the scope to the parent scope. scope.CanMergeWithParent = false; } // Prevent us repeating this process for all scopes if another jumps goes to the same label scopesAfterLabel.Clear(); } } #nullable enable private BoundNode? VisitNestedFunction(MethodSymbol functionSymbol, BoundBlock? body) { RoslynDebug.Assert(functionSymbol is object); if (body is null) { // extern closure _currentScope.NestedFunctions.Add(new NestedFunction(functionSymbol, blockSyntax: null)); return null; } // Nested function is declared (lives) in the parent scope, but its // variables are in a nested scope var function = new NestedFunction(functionSymbol, body.Syntax.GetReference()); _currentScope.NestedFunctions.Add(function); var oldFunction = _currentFunction; _currentFunction = function; var oldScope = _currentScope; CreateAndPushScope(body); // For the purposes of scoping, parameters live in the same scope as the // nested function block. Expression tree variables are free variables for the // purposes of closure conversion DeclareLocals(_currentScope, functionSymbol.Parameters, _inExpressionTree); var result = _inExpressionTree ? base.VisitBlock(body) : VisitBlock(body); PopScope(oldScope); _currentFunction = oldFunction; return result; } #nullable disable private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) { Debug.Assert( symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol.Kind == SymbolKind.Method); if (_currentFunction == null) { // Can't be captured if we're not in a nested function return; } if (symbol is LocalSymbol local && local.IsConst) { // consts aren't captured since they're inlined return; } if (symbol is MethodSymbol method && _currentFunction.OriginalMethodSymbol == method) { // Is this recursion? If so there's no capturing return; } Debug.Assert(symbol.ContainingSymbol != null); if (symbol.ContainingSymbol != _currentFunction.OriginalMethodSymbol) { // Restricted types can't be hoisted, so they are not permitted to be captured AddDiagnosticIfRestrictedType(symbol, syntax); // Record the captured variable where it's captured var scope = _currentScope; var function = _currentFunction; while (function != null && symbol.ContainingSymbol != function.OriginalMethodSymbol) { function.CapturedVariables.Add(symbol); // Also mark captured in enclosing scopes while (scope.ContainingFunctionOpt == function) { scope = scope.Parent; } function = scope.ContainingFunctionOpt; } // Also record where the captured variable lives // No need to record where local functions live: that was recorded // in the NestedFunctions list in each scope if (symbol.Kind == SymbolKind.Method) { return; } if (_localToScope.TryGetValue(symbol, out var declScope)) { declScope.DeclaredVariables.Add(symbol); } else { #if DEBUG // Parameters and locals from expression tree lambdas // are free variables Debug.Assert(_freeVariables.Contains(symbol)); #endif } } } /// <summary> /// Add a diagnostic if the type of a captured variable is a restricted type /// </summary> private void AddDiagnosticIfRestrictedType(Symbol capturedVariable, SyntaxNode syntax) { TypeSymbol type; switch (capturedVariable.Kind) { case SymbolKind.Local: type = ((LocalSymbol)capturedVariable).Type; break; case SymbolKind.Parameter: type = ((ParameterSymbol)capturedVariable).Type; break; default: // This should only be called for captured variables, and captured // variables must be a method, parameter, or local symbol Debug.Assert(capturedVariable.Kind == SymbolKind.Method); return; } if (type.IsRestrictedType() == true) { _diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } /// <summary> /// Create a new nested scope under the current scope, and replace <see cref="_currentScope"/> with the new scope, /// or reuse the current scope if there's no change in the bound node for the nested scope. /// Records the given locals as declared in the aforementioned scope. /// </summary> private void PushOrReuseScope<TSymbol>(BoundNode node, ImmutableArray<TSymbol> locals) where TSymbol : Symbol { // We should never create a new scope with the same bound node. We can get into // this situation for methods and nested functions where a new scope is created // to add parameters and a new scope would be created for the method block, // despite the fact that they should be the same scope. if (!locals.IsEmpty && _currentScope.BoundNode != node) { CreateAndPushScope(node); } DeclareLocals(_currentScope, locals); } /// <summary> /// Creates a new nested scope which is a child of <see cref="_currentScope"/>, /// and replaces <see cref="_currentScope"/> with the new scope /// </summary> /// <param name="node"></param> private void CreateAndPushScope(BoundNode node) { var scope = CreateNestedScope(_currentScope, _currentFunction); foreach (var label in _labelsInScope.Peek()) { _scopesAfterLabel[label].Add(scope); } _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _currentScope = scope; Scope CreateNestedScope(Scope parentScope, NestedFunction currentFunction) { Debug.Assert(parentScope.BoundNode != node); var newScope = new Scope(parentScope, node, currentFunction); parentScope.NestedScopes.Add(newScope); return newScope; } } /// <summary> /// Requires that scope is either the same as <see cref="_currentScope"/>, /// or is the <see cref="Scope.Parent"/> of <see cref="_currentScope"/>. /// Returns immediately in the first case, /// Replaces <see cref="_currentScope"/> with scope in the second. /// </summary> /// <param name="scope"></param> private void PopScope(Scope scope) { if (scope == _currentScope) { return; } Debug.Assert(scope == _currentScope.Parent, $"{nameof(scope)} must be {nameof(_currentScope)} or {nameof(_currentScope)}.{nameof(_currentScope.Parent)}"); // Since it is forbidden to jump into a scope, // we can forget all information we have about labels in the child scope var labels = _labelsInScope.Pop(); foreach (var label in labels) { var scopes = _scopesAfterLabel[label]; scopes.Free(); _scopesAfterLabel.Remove(label); } labels.Free(); _currentScope = _currentScope.Parent; } private void DeclareLocals<TSymbol>(Scope scope, ImmutableArray<TSymbol> locals, bool declareAsFree = false) where TSymbol : Symbol { foreach (var local in locals) { Debug.Assert(!_localToScope.ContainsKey(local)); if (declareAsFree) { #if DEBUG Debug.Assert(_freeVariables.Add(local)); #endif } else { _localToScope.Add(local, scope); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ClosureConversion { internal sealed partial class Analysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// This is the core node for a Scope tree, which stores all semantically meaningful /// information about declared variables, closures, and environments in each scope. /// It can be thought of as the essence of the bound tree -- stripping away many of /// the unnecessary details stored in the bound tree and just leaving the pieces that /// are important for closure conversion. The root scope is the method scope for the /// method being analyzed and has a null <see cref="Parent" />. /// </summary> [DebuggerDisplay("{ToString(), nq}")] public sealed class Scope { public readonly Scope Parent; public readonly ArrayBuilder<Scope> NestedScopes = ArrayBuilder<Scope>.GetInstance(); /// <summary> /// A list of all nested functions (all lambdas and local functions) declared in this scope. /// </summary> public readonly ArrayBuilder<NestedFunction> NestedFunctions = ArrayBuilder<NestedFunction>.GetInstance(); /// <summary> /// A list of all locals or parameters that were declared in this scope and captured /// in this scope or nested scopes. "Declared" refers to the start of the variable /// lifetime (which, at this point in lowering, should be equivalent to lexical scope). /// </summary> /// <remarks> /// It's important that this is a set and that enumeration order is deterministic. We loop /// over this list to generate proxies and if we loop out of order this will cause /// non-deterministic compilation, and if we generate duplicate proxies we'll generate /// wasteful code in the best case and incorrect code in the worst. /// </remarks> public readonly SetWithInsertionOrder<Symbol> DeclaredVariables = new SetWithInsertionOrder<Symbol>(); /// <summary> /// The bound node representing this scope. This roughly corresponds to the bound /// node for the block declaring locals for this scope, although parameters of /// methods/functions are introduced into their Body's scope and do not get their /// own scope. /// </summary> public readonly BoundNode BoundNode; /// <summary> /// The nested function that this scope is nested inside. Null if this scope is not nested /// inside a nested function. /// </summary> public readonly NestedFunction ContainingFunctionOpt; #nullable enable /// <summary> /// Environment created in this scope to hold <see cref="DeclaredVariables"/>. /// At the moment, all variables declared in the same scope /// always get assigned to the same environment. /// </summary> public ClosureEnvironment? DeclaredEnvironment = null; #nullable disable public Scope(Scope parent, BoundNode boundNode, NestedFunction containingFunction) { Debug.Assert(boundNode != null); Parent = parent; BoundNode = boundNode; ContainingFunctionOpt = containingFunction; } /// <summary> /// Is it safe to move any of the variables declared in this scope to the parent scope, /// or would doing so change the meaning of the program? /// </summary> public bool CanMergeWithParent { get; internal set; } = true; public void Free() { foreach (var scope in NestedScopes) { scope.Free(); } NestedScopes.Free(); foreach (var function in NestedFunctions) { function.Free(); } NestedFunctions.Free(); } public override string ToString() => BoundNode.Syntax.GetText().ToString(); } /// <summary> /// The NestedFunction type represents a lambda or local function and stores /// information related to that function. After initially building the /// <see cref="Scope"/> tree the only information available is /// <see cref="OriginalMethodSymbol"/> and <see cref="CapturedVariables"/>. /// Subsequent passes are responsible for translating captured /// variables into captured environments and for calculating /// the rewritten signature of the method. /// </summary> public sealed class NestedFunction { /// <summary> /// The method symbol for the original lambda or local function. /// </summary> public readonly MethodSymbol OriginalMethodSymbol; /// <summary> /// Syntax for the block of the nested function. /// </summary> public readonly SyntaxReference BlockSyntax; public readonly PooledHashSet<Symbol> CapturedVariables = PooledHashSet<Symbol>.GetInstance(); public readonly ArrayBuilder<ClosureEnvironment> CapturedEnvironments = ArrayBuilder<ClosureEnvironment>.GetInstance(); public ClosureEnvironment ContainingEnvironmentOpt; private bool _capturesThis; /// <summary> /// True if this function directly or transitively captures 'this' (captures /// a local function which directly or indirectly captures 'this'). /// Calculated in <see cref="MakeAndAssignEnvironments"/>. /// </summary> public bool CapturesThis { get => _capturesThis; set { Debug.Assert(value); _capturesThis = value; } } public SynthesizedClosureMethod SynthesizedLoweredMethod; public NestedFunction(MethodSymbol symbol, SyntaxReference blockSyntax) { Debug.Assert(symbol != null); OriginalMethodSymbol = symbol; BlockSyntax = blockSyntax; } public void Free() { CapturedVariables.Free(); CapturedEnvironments.Free(); } } public sealed class ClosureEnvironment { public readonly SetWithInsertionOrder<Symbol> CapturedVariables; /// <summary> /// True if this environment captures a reference to a class environment /// declared in a higher scope. Assigned by /// <see cref="ComputeLambdaScopesAndFrameCaptures()"/> /// </summary> public bool CapturesParent; public readonly bool IsStruct; internal SynthesizedClosureEnvironment SynthesizedEnvironment; public ClosureEnvironment(IEnumerable<Symbol> capturedVariables, bool isStruct) { CapturedVariables = new SetWithInsertionOrder<Symbol>(); foreach (var item in capturedVariables) { CapturedVariables.Add(item); } IsStruct = isStruct; } } /// <summary> /// Visit all nested functions in all nested scopes and run the <paramref name="action"/>. /// </summary> public static void VisitNestedFunctions(Scope scope, Action<Scope, NestedFunction> action) { foreach (var function in scope.NestedFunctions) { action(scope, function); } foreach (var nested in scope.NestedScopes) { VisitNestedFunctions(nested, action); } } /// <summary> /// Visit all the functions and return true when the <paramref name="func"/> returns /// true. Otherwise, returns false. /// </summary> public static bool CheckNestedFunctions(Scope scope, Func<Scope, NestedFunction, bool> func) { foreach (var function in scope.NestedFunctions) { if (func(scope, function)) { return true; } } foreach (var nested in scope.NestedScopes) { if (CheckNestedFunctions(nested, func)) { return true; } } return false; } /// <summary> /// Visit the tree with the given root and run the <paramref name="action"/> /// </summary> public static void VisitScopeTree(Scope treeRoot, Action<Scope> action) { action(treeRoot); foreach (var nested in treeRoot.NestedScopes) { VisitScopeTree(nested, action); } } /// <summary> /// Builds a tree of <see cref="Scope"/> nodes corresponding to a given method. /// <see cref="Build(BoundNode, MethodSymbol, HashSet{MethodSymbol}, DiagnosticBag)"/> /// visits the bound tree and translates information from the bound tree about /// variable scope, declared variables, and variable captures into the resulting /// <see cref="Scope"/> tree. /// /// At the same time it sets <see cref="Scope.CanMergeWithParent"/> /// for each Scope. This is done by looking for <see cref="BoundGotoStatement"/>s /// and <see cref="BoundConditionalGoto"/>s that jump from a point /// after the beginning of a <see cref="Scope"/>, to a <see cref="BoundLabelStatement"/> /// before the start of the scope, but after the start of <see cref="Scope.Parent"/>. /// /// All loops have been converted to gotos and labels by this stage, /// so we do not have to visit them to do so. Similarly all <see cref="BoundLabeledStatement"/>s /// have been converted to <see cref="BoundLabelStatement"/>s, so we do not have to /// visit them. /// </summary> private class ScopeTreeBuilder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Do not set this directly, except when setting the root scope. /// Instead use <see cref="PopScope"/> or <see cref="CreateAndPushScope"/>. /// </summary> private Scope _currentScope; /// <summary> /// Null if we're not inside a nested function, otherwise the nearest nested function. /// </summary> private NestedFunction _currentFunction = null; private bool _inExpressionTree = false; /// <summary> /// A mapping from all captured vars to the scope they were declared in. This /// is used when recording captured variables as we must know what the lifetime /// of a captured variable is to determine the lifetime of its capture environment. /// </summary> private readonly SmallDictionary<Symbol, Scope> _localToScope = new SmallDictionary<Symbol, Scope>(); #if DEBUG /// <summary> /// Free variables are variables declared in expression statements that can then /// be captured in nested lambdas. Normally, captured variables must lowered as /// part of closure conversion, but expression tree variables are handled separately /// by the expression tree rewriter and are considered free for the purposes of /// closure conversion. For instance, an expression with a nested lambda, e.g. /// x => y => x + y /// contains an expression variable, x, that should not be treated as a captured /// variable to be replaced by closure conversion. Instead, it should be left for /// expression tree conversion. /// </summary> private readonly HashSet<Symbol> _freeVariables = new HashSet<Symbol>(); #endif private readonly MethodSymbol _topLevelMethod; /// <summary> /// If a local function is in the set, at some point in the code it is converted /// to a delegate and should then not be optimized to a struct closure. /// Also contains all lambdas (as they are converted to delegates implicitly). /// </summary> private readonly HashSet<MethodSymbol> _methodsConvertedToDelegates; private readonly DiagnosticBag _diagnostics; /// <summary> /// For every label visited so far, this dictionary maps to a list of all scopes either visited so far, or currently being visited, /// that are both after the label, and are on the same level of the scope tree as the label. /// </summary> private readonly PooledDictionary<LabelSymbol, ArrayBuilder<Scope>> _scopesAfterLabel = PooledDictionary<LabelSymbol, ArrayBuilder<Scope>>.GetInstance(); /// <summary> /// Contains a list of the labels visited so far for each scope. /// The outer ArrayBuilder is a stack representing the chain of scopes from the root scope to the current scope, /// and for each item on the stack, the ArrayBuilder is the list of the labels visited so far for the scope. /// /// Used by <see cref="CreateAndPushScope"/> to determine which labels a new child scope appears after. /// </summary> private readonly ArrayBuilder<ArrayBuilder<LabelSymbol>> _labelsInScope = ArrayBuilder<ArrayBuilder<LabelSymbol>>.GetInstance(); private ScopeTreeBuilder( Scope rootScope, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { Debug.Assert(rootScope != null); Debug.Assert(topLevelMethod != null); Debug.Assert(methodsConvertedToDelegates != null); Debug.Assert(diagnostics != null); _currentScope = rootScope; _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _topLevelMethod = topLevelMethod; _methodsConvertedToDelegates = methodsConvertedToDelegates; _diagnostics = diagnostics; } public static Scope Build( BoundNode node, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { // This should be the top-level node Debug.Assert(node == FindNodeToAnalyze(node)); Debug.Assert(topLevelMethod != null); var rootScope = new Scope(parent: null, boundNode: node, containingFunction: null); var builder = new ScopeTreeBuilder( rootScope, topLevelMethod, methodsConvertedToDelegates, diagnostics); builder.Build(); return rootScope; } private void Build() { // Set up the current method locals DeclareLocals(_currentScope, _topLevelMethod.Parameters); // Treat 'this' as a formal parameter of the top-level method if (_topLevelMethod.TryGetThisParameter(out var thisParam) && (object)thisParam != null) { DeclareLocals(_currentScope, ImmutableArray.Create<Symbol>(thisParam)); } Visit(_currentScope.BoundNode); // Clean Up Resources foreach (var scopes in _scopesAfterLabel.Values) { scopes.Free(); } _scopesAfterLabel.Free(); Debug.Assert(_labelsInScope.Count == 1); var labels = _labelsInScope.Pop(); labels.Free(); _labelsInScope.Free(); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) => throw ExceptionUtilities.Unreachable; public override BoundNode VisitBlock(BoundBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitCatchBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitSequence(BoundSequence node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitSequence(node); PopScope(oldScope); return result; } public override BoundNode VisitLambda(BoundLambda node) { var oldInExpressionTree = _inExpressionTree; _inExpressionTree |= node.Type.IsExpressionTree(); _methodsConvertedToDelegates.Add(node.Symbol.OriginalDefinition); var result = VisitNestedFunction(node.Symbol, node.Body); _inExpressionTree = oldInExpressionTree; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) => VisitNestedFunction(node.Symbol.OriginalDefinition, node.Body); public override BoundNode VisitCall(BoundCall node) { if (node.Method.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters AddIfCaptured(node.Method.OriginalDefinition, node.Syntax); } return base.VisitCall(node); } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters var method = node.MethodOpt.OriginalDefinition; AddIfCaptured(method, node.Syntax); _methodsConvertedToDelegates.Add(method); } return base.VisitDelegateCreationExpression(node); } public override BoundNode VisitParameter(BoundParameter node) { AddIfCaptured(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } public override BoundNode VisitLocal(BoundLocal node) { AddIfCaptured(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { AddIfCaptured(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitThisReference(BoundThisReference node) { var thisParam = _topLevelMethod.ThisParameter; if (thisParam != null) { AddIfCaptured(thisParam, node.Syntax); } else { // This can occur in a delegate creation expression because the method group // in the argument can have a "this" receiver even when "this" // is not captured because a static method is selected. But we do preserve // the method group and its receiver in the bound tree. // No need to capture "this" in such case. // TODO: Why don't we drop "this" while lowering if method is static? // Actually, considering that method group expression does not evaluate to a particular value // why do we have it in the lowered tree at all? } return base.VisitThisReference(node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { _labelsInScope.Peek().Add(node.Label); _scopesAfterLabel.Add(node.Label, ArrayBuilder<Scope>.GetInstance()); return base.VisitLabelStatement(node); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { CheckCanMergeWithParent(node.Label); return base.VisitGotoStatement(node); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { CheckCanMergeWithParent(node.Label); return base.VisitConditionalGoto(node); } /// <summary> /// This is where we calculate <see cref="Scope.CanMergeWithParent"/>. /// <see cref="Scope.CanMergeWithParent"/> is always true unless we jump from after /// the beginning of a scope, to a point in between the beginning of the parent scope, and the beginning of the scope /// </summary> /// <param name="jumpTarget"></param> private void CheckCanMergeWithParent(LabelSymbol jumpTarget) { // since forward jumps can never effect Scope.SemanticallySafeToMergeIntoParent // if we have not yet seen the jumpTarget, this is a forward jump, and can be ignored if (_scopesAfterLabel.TryGetValue(jumpTarget, out var scopesAfterLabel)) { foreach (var scope in scopesAfterLabel) { // this jump goes from a point after the beginning of the scope (as we have already visited or started visiting the scope), // to a point in between the beginning of the parent scope, and the beginning of the scope, so it is not safe to move // variables in the scope to the parent scope. scope.CanMergeWithParent = false; } // Prevent us repeating this process for all scopes if another jumps goes to the same label scopesAfterLabel.Clear(); } } #nullable enable private BoundNode? VisitNestedFunction(MethodSymbol functionSymbol, BoundBlock? body) { RoslynDebug.Assert(functionSymbol is object); if (body is null) { // extern closure _currentScope.NestedFunctions.Add(new NestedFunction(functionSymbol, blockSyntax: null)); return null; } // Nested function is declared (lives) in the parent scope, but its // variables are in a nested scope var function = new NestedFunction(functionSymbol, body.Syntax.GetReference()); _currentScope.NestedFunctions.Add(function); var oldFunction = _currentFunction; _currentFunction = function; var oldScope = _currentScope; CreateAndPushScope(body); // For the purposes of scoping, parameters live in the same scope as the // nested function block. Expression tree variables are free variables for the // purposes of closure conversion DeclareLocals(_currentScope, functionSymbol.Parameters, _inExpressionTree); var result = _inExpressionTree ? base.VisitBlock(body) : VisitBlock(body); PopScope(oldScope); _currentFunction = oldFunction; return result; } #nullable disable private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) { Debug.Assert( symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol.Kind == SymbolKind.Method); if (_currentFunction == null) { // Can't be captured if we're not in a nested function return; } if (symbol is LocalSymbol local && local.IsConst) { // consts aren't captured since they're inlined return; } if (symbol is MethodSymbol method && _currentFunction.OriginalMethodSymbol == method) { // Is this recursion? If so there's no capturing return; } Debug.Assert(symbol.ContainingSymbol != null); if (symbol.ContainingSymbol != _currentFunction.OriginalMethodSymbol) { // Restricted types can't be hoisted, so they are not permitted to be captured AddDiagnosticIfRestrictedType(symbol, syntax); // Record the captured variable where it's captured var scope = _currentScope; var function = _currentFunction; while (function != null && symbol.ContainingSymbol != function.OriginalMethodSymbol) { function.CapturedVariables.Add(symbol); // Also mark captured in enclosing scopes while (scope.ContainingFunctionOpt == function) { scope = scope.Parent; } function = scope.ContainingFunctionOpt; } // Also record where the captured variable lives // No need to record where local functions live: that was recorded // in the NestedFunctions list in each scope if (symbol.Kind == SymbolKind.Method) { return; } if (_localToScope.TryGetValue(symbol, out var declScope)) { declScope.DeclaredVariables.Add(symbol); } else { #if DEBUG // Parameters and locals from expression tree lambdas // are free variables Debug.Assert(_freeVariables.Contains(symbol)); #endif } } } /// <summary> /// Add a diagnostic if the type of a captured variable is a restricted type /// </summary> private void AddDiagnosticIfRestrictedType(Symbol capturedVariable, SyntaxNode syntax) { TypeSymbol type; switch (capturedVariable.Kind) { case SymbolKind.Local: type = ((LocalSymbol)capturedVariable).Type; break; case SymbolKind.Parameter: type = ((ParameterSymbol)capturedVariable).Type; break; default: // This should only be called for captured variables, and captured // variables must be a method, parameter, or local symbol Debug.Assert(capturedVariable.Kind == SymbolKind.Method); return; } if (type.IsRestrictedType() == true) { _diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } /// <summary> /// Create a new nested scope under the current scope, and replace <see cref="_currentScope"/> with the new scope, /// or reuse the current scope if there's no change in the bound node for the nested scope. /// Records the given locals as declared in the aforementioned scope. /// </summary> private void PushOrReuseScope<TSymbol>(BoundNode node, ImmutableArray<TSymbol> locals) where TSymbol : Symbol { // We should never create a new scope with the same bound node. We can get into // this situation for methods and nested functions where a new scope is created // to add parameters and a new scope would be created for the method block, // despite the fact that they should be the same scope. if (!locals.IsEmpty && _currentScope.BoundNode != node) { CreateAndPushScope(node); } DeclareLocals(_currentScope, locals); } /// <summary> /// Creates a new nested scope which is a child of <see cref="_currentScope"/>, /// and replaces <see cref="_currentScope"/> with the new scope /// </summary> /// <param name="node"></param> private void CreateAndPushScope(BoundNode node) { var scope = CreateNestedScope(_currentScope, _currentFunction); foreach (var label in _labelsInScope.Peek()) { _scopesAfterLabel[label].Add(scope); } _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _currentScope = scope; Scope CreateNestedScope(Scope parentScope, NestedFunction currentFunction) { Debug.Assert(parentScope.BoundNode != node); var newScope = new Scope(parentScope, node, currentFunction); parentScope.NestedScopes.Add(newScope); return newScope; } } /// <summary> /// Requires that scope is either the same as <see cref="_currentScope"/>, /// or is the <see cref="Scope.Parent"/> of <see cref="_currentScope"/>. /// Returns immediately in the first case, /// Replaces <see cref="_currentScope"/> with scope in the second. /// </summary> /// <param name="scope"></param> private void PopScope(Scope scope) { if (scope == _currentScope) { return; } Debug.Assert(scope == _currentScope.Parent, $"{nameof(scope)} must be {nameof(_currentScope)} or {nameof(_currentScope)}.{nameof(_currentScope.Parent)}"); // Since it is forbidden to jump into a scope, // we can forget all information we have about labels in the child scope var labels = _labelsInScope.Pop(); foreach (var label in labels) { var scopes = _scopesAfterLabel[label]; scopes.Free(); _scopesAfterLabel.Remove(label); } labels.Free(); _currentScope = _currentScope.Parent; } private void DeclareLocals<TSymbol>(Scope scope, ImmutableArray<TSymbol> locals, bool declareAsFree = false) where TSymbol : Symbol { foreach (var local in locals) { Debug.Assert(!_localToScope.ContainsKey(local)); if (declareAsFree) { #if DEBUG Debug.Assert(_freeVariables.Add(local)); #endif } else { _localToScope.Add(local, scope); } } } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/PerformanceFunctionIdPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { [Guid(Guids.RoslynOptionPagePerformanceFunctionIdIdString)] internal class PerformanceFunctionIdPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { return new InternalOptionsControl(nameof(FunctionIdOptions), optionStore); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { [Guid(Guids.RoslynOptionPagePerformanceFunctionIdIdString)] internal class PerformanceFunctionIdPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { return new InternalOptionsControl(nameof(FunctionIdOptions), optionStore); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarController_ModelComputation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Threading; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal partial class NavigationBarController { /// <summary> /// Starts a new task to compute the model based on the current text. /// </summary> private async ValueTask<NavigationBarModel> ComputeModelAndSelectItemAsync(ImmutableArray<bool> unused, CancellationToken cancellationToken) { // Jump back to the UI thread to determine what snapshot the user is processing. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textSnapshot = _subjectBuffer.CurrentSnapshot; // Ensure we switch to the threadpool before calling GetDocumentWithFrozenPartialSemantics. It ensures // that any IO that performs is not potentially on the UI thread. await TaskScheduler.Default; var model = await ComputeModelAsync(textSnapshot, cancellationToken).ConfigureAwait(false); await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Now, enqueue work to select the right item in this new model. StartSelectedItemUpdateTask(); return model; static async Task<NavigationBarModel> ComputeModelAsync(ITextSnapshot textSnapshot, CancellationToken cancellationToken) { // When computing items just get the partial semantics workspace. This will ensure we can get data for this // file, and hopefully have enough loaded to get data for other files in the case of partial types. In the // event the other files aren't available, then partial-type information won't be correct. That's ok though // as this is just something that happens during solution load and will pass once that is over. By using // partial semantics, we can ensure we don't spend an inordinate amount of time computing and using full // compilation data (like skeleton assemblies). var document = textSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document == null) return null; var itemService = document.GetLanguageService<INavigationBarItemService>(); if (itemService != null) { using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken)) { var items = await itemService.GetItemsAsync(document, textSnapshot, cancellationToken).ConfigureAwait(false); return new NavigationBarModel(items, itemService); } } return new NavigationBarModel(ImmutableArray<NavigationBarItem>.Empty, itemService: null); } } /// <summary> /// Starts a new task to compute what item should be selected. /// </summary> private void StartSelectedItemUpdateTask() { // 'true' value is unused. this just signals to the queue that we have work to do. _selectItemQueue.AddWork(); } private async ValueTask SelectItemAsync(CancellationToken cancellationToken) { // Switch to the UI so we can determine where the user is. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var currentView = _presenter.TryGetCurrentView(); var caretPosition = currentView?.GetCaretPoint(_subjectBuffer); if (!caretPosition.HasValue) return; // Ensure the latest model is computed and grab it while on the UI thread. var model = await _computeModelQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(true); // Jump back to the BG to do any expensive work walking the entire model await TaskScheduler.Default; var currentSelectedItem = ComputeSelectedTypeAndMember(model, caretPosition.Value, cancellationToken); // Finally, switch back to the UI to update our state and UI. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Update the UI to show *just* the type/member that was selected. We don't need it to know about all items // as the user can only see one at a time as they're editing in a document. However, once we've done this, // store the full list of items as well so that if the user expands the dropdown, we can take all those // values and shove them in so it appears as if the lists were always fully realized. _latestModelAndSelectedInfo_OnlyAccessOnUIThread = (model, currentSelectedItem); PushSelectedItemsToPresenter(currentSelectedItem); } internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember(NavigationBarModel model, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var (item, gray) = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken); if (item == null) { // Nothing to show at all return new NavigationBarSelectedTypeAndMember(null, null); } var rightItem = GetMatchingItem(item.ChildItems, caretPosition, model.ItemService, cancellationToken); return new NavigationBarSelectedTypeAndMember(item, gray, rightItem.item, rightItem.gray); } /// <summary> /// Finds the item that point is in, or if it's not in any items, gets the first item that's /// positioned after the cursor. /// </summary> /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns> private static (T item, bool gray) GetMatchingItem<T>(IEnumerable<T> items, SnapshotPoint point, INavigationBarItemService itemsService, CancellationToken cancellationToken) where T : NavigationBarItem { T exactItem = null; var exactItemStart = 0; T nextItem = null; var nextItemStart = int.MaxValue; foreach (var item in items) { foreach (var trackingSpan in item.TrackingSpans) { cancellationToken.ThrowIfCancellationRequested(); var span = trackingSpan.GetSpan(point.Snapshot); if (span.Contains(point) || span.End == point) { // This is the item we should show normally. We'll continue looking at other // items as there might be a nested type that we're actually in. If there // are multiple items containing the point, choose whichever containing span // starts later because that will be the most nested item. if (exactItem == null || span.Start >= exactItemStart) { exactItem = item; exactItemStart = span.Start; } } else if (span.Start > point && span.Start <= nextItemStart) { nextItem = item; nextItemStart = span.Start; } } } if (exactItem != null) { return (exactItem, gray: false); } else { // The second parameter is if we should show it grayed. We'll be nice and say false // unless we actually have an item var itemToGray = nextItem ?? items.LastOrDefault(); if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray)) { itemToGray = null; } return (itemToGray, gray: itemToGray != 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Threading; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal partial class NavigationBarController { /// <summary> /// Starts a new task to compute the model based on the current text. /// </summary> private async ValueTask<NavigationBarModel> ComputeModelAndSelectItemAsync(ImmutableArray<bool> unused, CancellationToken cancellationToken) { // Jump back to the UI thread to determine what snapshot the user is processing. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textSnapshot = _subjectBuffer.CurrentSnapshot; // Ensure we switch to the threadpool before calling GetDocumentWithFrozenPartialSemantics. It ensures // that any IO that performs is not potentially on the UI thread. await TaskScheduler.Default; var model = await ComputeModelAsync(textSnapshot, cancellationToken).ConfigureAwait(false); await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Now, enqueue work to select the right item in this new model. StartSelectedItemUpdateTask(); return model; static async Task<NavigationBarModel> ComputeModelAsync(ITextSnapshot textSnapshot, CancellationToken cancellationToken) { // When computing items just get the partial semantics workspace. This will ensure we can get data for this // file, and hopefully have enough loaded to get data for other files in the case of partial types. In the // event the other files aren't available, then partial-type information won't be correct. That's ok though // as this is just something that happens during solution load and will pass once that is over. By using // partial semantics, we can ensure we don't spend an inordinate amount of time computing and using full // compilation data (like skeleton assemblies). var document = textSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document == null) return null; var itemService = document.GetLanguageService<INavigationBarItemService>(); if (itemService != null) { using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken)) { var items = await itemService.GetItemsAsync(document, textSnapshot, cancellationToken).ConfigureAwait(false); return new NavigationBarModel(items, itemService); } } return new NavigationBarModel(ImmutableArray<NavigationBarItem>.Empty, itemService: null); } } /// <summary> /// Starts a new task to compute what item should be selected. /// </summary> private void StartSelectedItemUpdateTask() { // 'true' value is unused. this just signals to the queue that we have work to do. _selectItemQueue.AddWork(); } private async ValueTask SelectItemAsync(CancellationToken cancellationToken) { // Switch to the UI so we can determine where the user is. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var currentView = _presenter.TryGetCurrentView(); var caretPosition = currentView?.GetCaretPoint(_subjectBuffer); if (!caretPosition.HasValue) return; // Ensure the latest model is computed and grab it while on the UI thread. var model = await _computeModelQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(true); // Jump back to the BG to do any expensive work walking the entire model await TaskScheduler.Default; var currentSelectedItem = ComputeSelectedTypeAndMember(model, caretPosition.Value, cancellationToken); // Finally, switch back to the UI to update our state and UI. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Update the UI to show *just* the type/member that was selected. We don't need it to know about all items // as the user can only see one at a time as they're editing in a document. However, once we've done this, // store the full list of items as well so that if the user expands the dropdown, we can take all those // values and shove them in so it appears as if the lists were always fully realized. _latestModelAndSelectedInfo_OnlyAccessOnUIThread = (model, currentSelectedItem); PushSelectedItemsToPresenter(currentSelectedItem); } internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember(NavigationBarModel model, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var (item, gray) = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken); if (item == null) { // Nothing to show at all return new NavigationBarSelectedTypeAndMember(null, null); } var rightItem = GetMatchingItem(item.ChildItems, caretPosition, model.ItemService, cancellationToken); return new NavigationBarSelectedTypeAndMember(item, gray, rightItem.item, rightItem.gray); } /// <summary> /// Finds the item that point is in, or if it's not in any items, gets the first item that's /// positioned after the cursor. /// </summary> /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns> private static (T item, bool gray) GetMatchingItem<T>(IEnumerable<T> items, SnapshotPoint point, INavigationBarItemService itemsService, CancellationToken cancellationToken) where T : NavigationBarItem { T exactItem = null; var exactItemStart = 0; T nextItem = null; var nextItemStart = int.MaxValue; foreach (var item in items) { foreach (var trackingSpan in item.TrackingSpans) { cancellationToken.ThrowIfCancellationRequested(); var span = trackingSpan.GetSpan(point.Snapshot); if (span.Contains(point) || span.End == point) { // This is the item we should show normally. We'll continue looking at other // items as there might be a nested type that we're actually in. If there // are multiple items containing the point, choose whichever containing span // starts later because that will be the most nested item. if (exactItem == null || span.Start >= exactItemStart) { exactItem = item; exactItemStart = span.Start; } } else if (span.Start > point && span.Start <= nextItemStart) { nextItem = item; nextItemStart = span.Start; } } } if (exactItem != null) { return (exactItem, gray: false); } else { // The second parameter is if we should show it grayed. We'll be nice and say false // unless we actually have an item var itemToGray = nextItem ?? items.LastOrDefault(); if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray)) { itemToGray = null; } return (itemToGray, gray: itemToGray != null); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/Compilation/TypeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public readonly struct TypeInfo : IEquatable<TypeInfo> { internal static readonly TypeInfo None = new TypeInfo(type: null, convertedType: null, nullability: default, convertedNullability: default); /// <summary> /// The type of the expression represented by the syntax node. For expressions that do not /// have a type, null is returned. If the type could not be determined due to an error, then /// an IErrorTypeSymbol is returned. /// </summary> public ITypeSymbol? Type { get; } /// <summary> /// The top-level nullability information of the expression represented by the syntax node. /// </summary> public NullabilityInfo Nullability { get; } /// <summary> /// The type of the expression after it has undergone an implicit conversion. If the type /// did not undergo an implicit conversion, returns the same as Type. /// </summary> public ITypeSymbol? ConvertedType { get; } /// <summary> /// The top-level nullability of the expression after it has undergone an implicit conversion. /// For most expressions, this will be the same as the type. It can change in situations such /// as implicit user-defined conversions that have a nullable return type. /// </summary> public NullabilityInfo ConvertedNullability { get; } internal TypeInfo(ITypeSymbol? type, ITypeSymbol? convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability) : this() { Debug.Assert(type is null || type.NullableAnnotation == nullability.FlowState.ToAnnotation()); Debug.Assert(convertedType is null || convertedType.NullableAnnotation == convertedNullability.FlowState.ToAnnotation()); this.Type = type; this.Nullability = nullability; this.ConvertedType = convertedType; this.ConvertedNullability = convertedNullability; } public bool Equals(TypeInfo other) { return object.Equals(this.Type, other.Type) && object.Equals(this.ConvertedType, other.ConvertedType) && this.Nullability.Equals(other.Nullability) && this.ConvertedNullability.Equals(other.ConvertedNullability); } public override bool Equals(object? obj) { return obj is TypeInfo && this.Equals((TypeInfo)obj); } public override int GetHashCode() { return Hash.Combine(this.ConvertedType, Hash.Combine(this.Type, Hash.Combine(this.Nullability.GetHashCode(), this.ConvertedNullability.GetHashCode()))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public readonly struct TypeInfo : IEquatable<TypeInfo> { internal static readonly TypeInfo None = new TypeInfo(type: null, convertedType: null, nullability: default, convertedNullability: default); /// <summary> /// The type of the expression represented by the syntax node. For expressions that do not /// have a type, null is returned. If the type could not be determined due to an error, then /// an IErrorTypeSymbol is returned. /// </summary> public ITypeSymbol? Type { get; } /// <summary> /// The top-level nullability information of the expression represented by the syntax node. /// </summary> public NullabilityInfo Nullability { get; } /// <summary> /// The type of the expression after it has undergone an implicit conversion. If the type /// did not undergo an implicit conversion, returns the same as Type. /// </summary> public ITypeSymbol? ConvertedType { get; } /// <summary> /// The top-level nullability of the expression after it has undergone an implicit conversion. /// For most expressions, this will be the same as the type. It can change in situations such /// as implicit user-defined conversions that have a nullable return type. /// </summary> public NullabilityInfo ConvertedNullability { get; } internal TypeInfo(ITypeSymbol? type, ITypeSymbol? convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability) : this() { Debug.Assert(type is null || type.NullableAnnotation == nullability.FlowState.ToAnnotation()); Debug.Assert(convertedType is null || convertedType.NullableAnnotation == convertedNullability.FlowState.ToAnnotation()); this.Type = type; this.Nullability = nullability; this.ConvertedType = convertedType; this.ConvertedNullability = convertedNullability; } public bool Equals(TypeInfo other) { return object.Equals(this.Type, other.Type) && object.Equals(this.ConvertedType, other.ConvertedType) && this.Nullability.Equals(other.Nullability) && this.ConvertedNullability.Equals(other.ConvertedNullability); } public override bool Equals(object? obj) { return obj is TypeInfo && this.Equals((TypeInfo)obj); } public override int GetHashCode() { return Hash.Combine(this.ConvertedType, Hash.Combine(this.Type, Hash.Combine(this.Nullability.GetHashCode(), this.ConvertedNullability.GetHashCode()))); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class State { public SemanticDocument SemanticDocument { get; } public TTypeDeclarationSyntax TypeNode { get; set; } public string TypeName { get; set; } public string DocumentNameWithoutExtension { get; set; } public bool IsDocumentNameAValidIdentifier { get; set; } private State(SemanticDocument document) => SemanticDocument = document; internal static State Generate( SemanticDocument document, TTypeDeclarationSyntax typeDeclaration, CancellationToken cancellationToken) { var state = new State(document); if (!state.TryInitialize(typeDeclaration, cancellationToken)) { return null; } return state; } private bool TryInitialize( TTypeDeclarationSyntax typeDeclaration, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return false; } var tree = SemanticDocument.SyntaxTree; var root = SemanticDocument.Root; var syntaxFacts = SemanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); // compiler declared types, anonymous types, types defined in metadata should be filtered out. if (SemanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) is not INamedTypeSymbol typeSymbol || typeSymbol.Locations.Any(loc => loc.IsInMetadata) || typeSymbol.IsAnonymousType || typeSymbol.IsImplicitlyDeclared || typeSymbol.Name == string.Empty) { return false; } TypeNode = typeDeclaration; TypeName = typeSymbol.Name; DocumentNameWithoutExtension = Path.GetFileNameWithoutExtension(SemanticDocument.Document.Name); IsDocumentNameAValidIdentifier = syntaxFacts.IsValidIdentifier(DocumentNameWithoutExtension); return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class State { public SemanticDocument SemanticDocument { get; } public TTypeDeclarationSyntax TypeNode { get; set; } public string TypeName { get; set; } public string DocumentNameWithoutExtension { get; set; } public bool IsDocumentNameAValidIdentifier { get; set; } private State(SemanticDocument document) => SemanticDocument = document; internal static State Generate( SemanticDocument document, TTypeDeclarationSyntax typeDeclaration, CancellationToken cancellationToken) { var state = new State(document); if (!state.TryInitialize(typeDeclaration, cancellationToken)) { return null; } return state; } private bool TryInitialize( TTypeDeclarationSyntax typeDeclaration, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return false; } var tree = SemanticDocument.SyntaxTree; var root = SemanticDocument.Root; var syntaxFacts = SemanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); // compiler declared types, anonymous types, types defined in metadata should be filtered out. if (SemanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) is not INamedTypeSymbol typeSymbol || typeSymbol.Locations.Any(loc => loc.IsInMetadata) || typeSymbol.IsAnonymousType || typeSymbol.IsImplicitlyDeclared || typeSymbol.Name == string.Empty) { return false; } TypeNode = typeDeclaration; TypeName = typeSymbol.Name; DocumentNameWithoutExtension = Path.GetFileNameWithoutExtension(SemanticDocument.Document.Name); IsDocumentNameAValidIdentifier = syntaxFacts.IsValidIdentifier(DocumentNameWithoutExtension); return true; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public class ProjectDiagnostic : WorkspaceDiagnostic { public ProjectId ProjectId { get; } public ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId) : base(kind, message) { this.ProjectId = projectId; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public class ProjectDiagnostic : WorkspaceDiagnostic { public ProjectId ProjectId { get; } public ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId) : base(kind, message) { this.ProjectId = projectId; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DecimalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInChecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = checked($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnchecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = unchecked($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(decimal x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DecimalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInChecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = checked($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnchecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = unchecked($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(decimal x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/QuickInfo/QuickInfoOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.QuickInfo { internal static class QuickInfoOptions { public static readonly PerLanguageOption2<bool> ShowRemarksInQuickInfo = new(nameof(QuickInfoOptions), nameof(ShowRemarksInQuickInfo), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowRemarks")); public static readonly Option2<bool> IncludeNavigationHintsInQuickInfo = new(nameof(QuickInfoOptions), nameof(IncludeNavigationHintsInQuickInfo), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.Specific.IncludeNavigationHintsInQuickInfo")); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.QuickInfo { internal static class QuickInfoOptions { public static readonly PerLanguageOption2<bool> ShowRemarksInQuickInfo = new(nameof(QuickInfoOptions), nameof(ShowRemarksInQuickInfo), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowRemarks")); public static readonly Option2<bool> IncludeNavigationHintsInQuickInfo = new(nameof(QuickInfoOptions), nameof(IncludeNavigationHintsInQuickInfo), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.Specific.IncludeNavigationHintsInQuickInfo")); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Analyzers/Core/Analyzers/ConvertAnonymousTypeToTuple/AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.ConvertAnonymousTypeToTuple { internal abstract class AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer< TSyntaxKind, TAnonymousObjectCreationExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TAnonymousObjectCreationExpressionSyntax : SyntaxNode { private readonly ISyntaxKinds _syntaxKinds; protected AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(ISyntaxKinds syntaxKinds) : base(IDEDiagnosticIds.ConvertAnonymousTypeToTupleDiagnosticId, EnforceOnBuildValues.ConvertAnonymousTypeToTuple, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), // This analyzer is not configurable. The intent is just to act as a refactoring, just benefiting from fix-all configurable: false) { _syntaxKinds = syntaxKinds; } protected abstract int GetInitializerCount(TAnonymousObjectCreationExpressionSyntax anonymousType); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction( AnalyzeSyntax, _syntaxKinds.Convert<TSyntaxKind>(_syntaxKinds.AnonymousObjectCreationExpression)); // Analysis is trivial. All anonymous types with more than two fields are marked as being // convertible to a tuple. private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var anonymousType = (TAnonymousObjectCreationExpressionSyntax)context.Node; if (GetInitializerCount(anonymousType) < 2) { return; } context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Node.GetFirstToken().GetLocation(), ReportDiagnostic.Hidden, additionalLocations: null, properties: null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.ConvertAnonymousTypeToTuple { internal abstract class AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer< TSyntaxKind, TAnonymousObjectCreationExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TAnonymousObjectCreationExpressionSyntax : SyntaxNode { private readonly ISyntaxKinds _syntaxKinds; protected AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(ISyntaxKinds syntaxKinds) : base(IDEDiagnosticIds.ConvertAnonymousTypeToTupleDiagnosticId, EnforceOnBuildValues.ConvertAnonymousTypeToTuple, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), // This analyzer is not configurable. The intent is just to act as a refactoring, just benefiting from fix-all configurable: false) { _syntaxKinds = syntaxKinds; } protected abstract int GetInitializerCount(TAnonymousObjectCreationExpressionSyntax anonymousType); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction( AnalyzeSyntax, _syntaxKinds.Convert<TSyntaxKind>(_syntaxKinds.AnonymousObjectCreationExpression)); // Analysis is trivial. All anonymous types with more than two fields are marked as being // convertible to a tuple. private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var anonymousType = (TAnonymousObjectCreationExpressionSyntax)context.Node; if (GetInitializerCount(anonymousType) < 2) { return; } context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Node.GetFirstToken().GetLocation(), ReportDiagnostic.Hidden, additionalLocations: null, properties: null)); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A class containing factory methods for constructing syntax nodes, tokens and trivia. /// </summary> public static partial class SyntaxFactory { /// <summary> /// A trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters. /// </summary> public static SyntaxTrivia CarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed; /// <summary> /// A trivia with kind EndOfLineTrivia containing a single line feed character. /// </summary> public static SyntaxTrivia LineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.LineFeed; /// <summary> /// A trivia with kind EndOfLineTrivia containing a single carriage return character. /// </summary> public static SyntaxTrivia CarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturn; /// <summary> /// A trivia with kind WhitespaceTrivia containing a single space character. /// </summary> public static SyntaxTrivia Space { get; } = Syntax.InternalSyntax.SyntaxFactory.Space; /// <summary> /// A trivia with kind WhitespaceTrivia containing a single tab character. /// </summary> public static SyntaxTrivia Tab { get; } = Syntax.InternalSyntax.SyntaxFactory.Tab; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters. /// Elastic trivia are used to denote trivia that was not produced by parsing source text, and are usually not /// preserved during formatting. /// </summary> public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing a single line feed character. Elastic trivia are used /// to denote trivia that was not produced by parsing source text, and are usually not preserved during /// formatting. /// </summary> public static SyntaxTrivia ElasticLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing a single carriage return character. Elastic trivia /// are used to denote trivia that was not produced by parsing source text, and are usually not preserved during /// formatting. /// </summary> public static SyntaxTrivia ElasticCarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing a single space character. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> public static SyntaxTrivia ElasticSpace { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticSpace; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing a single tab character. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> public static SyntaxTrivia ElasticTab { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticTab; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing no characters. Elastic marker trivia are included /// automatically by factory methods when trivia is not specified. Syntax formatting will replace elastic /// markers with appropriate trivia. /// </summary> public static SyntaxTrivia ElasticMarker { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace; /// <summary> /// Creates a trivia with kind EndOfLineTrivia containing the specified text. /// </summary> /// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and /// line feed characters are recognized by the parser as end of line.</param> public static SyntaxTrivia EndOfLine(string text) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: false); } /// <summary> /// Creates a trivia with kind EndOfLineTrivia containing the specified text. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> /// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and /// line feed characters are recognized by the parser as end of line.</param> public static SyntaxTrivia ElasticEndOfLine(string text) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true); } [Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SyntaxTrivia EndOfLine(string text, bool elastic) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic); } /// <summary> /// Creates a trivia with kind WhitespaceTrivia containing the specified text. /// </summary> /// <param name="text">The text of the whitespace. Any text can be specified here, however only specific /// whitespace characters are recognized by the parser.</param> public static SyntaxTrivia Whitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false); } /// <summary> /// Creates a trivia with kind WhitespaceTrivia containing the specified text. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> /// <param name="text">The text of the whitespace. Any text can be specified here, however only specific /// whitespace characters are recognized by the parser.</param> public static SyntaxTrivia ElasticWhitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false); } [Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SyntaxTrivia Whitespace(string text, bool elastic) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic); } /// <summary> /// Creates a trivia with kind either SingleLineCommentTrivia or MultiLineCommentTrivia containing the specified /// text. /// </summary> /// <param name="text">The entire text of the comment including the leading '//' token for single line comments /// or stop or start tokens for multiline comments.</param> public static SyntaxTrivia Comment(string text) { return Syntax.InternalSyntax.SyntaxFactory.Comment(text); } /// <summary> /// Creates a trivia with kind DisabledTextTrivia. Disabled text corresponds to any text between directives that /// is not considered active. /// </summary> public static SyntaxTrivia DisabledText(string text) { return Syntax.InternalSyntax.SyntaxFactory.DisabledText(text); } /// <summary> /// Creates a trivia with kind PreprocessingMessageTrivia. /// </summary> public static SyntaxTrivia PreprocessingMessage(string text) { return Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text); } /// <summary> /// Trivia nodes represent parts of the program text that are not parts of the /// syntactic grammar, such as spaces, newlines, comments, preprocessor /// directives, and disabled code. /// </summary> /// <param name="kind"> /// A <see cref="SyntaxKind"/> representing the specific kind of <see cref="SyntaxTrivia"/>. One of /// <see cref="SyntaxKind.WhitespaceTrivia"/>, <see cref="SyntaxKind.EndOfLineTrivia"/>, /// <see cref="SyntaxKind.SingleLineCommentTrivia"/>, <see cref="SyntaxKind.MultiLineCommentTrivia"/>, /// <see cref="SyntaxKind.DocumentationCommentExteriorTrivia"/>, <see cref="SyntaxKind.DisabledTextTrivia"/> /// </param> /// <param name="text"> /// The actual text of this token. /// </param> public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text) { if (text == null) { throw new ArgumentNullException(nameof(text)); } switch (kind) { case SyntaxKind.DisabledTextTrivia: case SyntaxKind.DocumentationCommentExteriorTrivia: case SyntaxKind.EndOfLineTrivia: case SyntaxKind.MultiLineCommentTrivia: case SyntaxKind.SingleLineCommentTrivia: case SyntaxKind.WhitespaceTrivia: return new SyntaxTrivia(default(SyntaxToken), new Syntax.InternalSyntax.SyntaxTrivia(kind, text, null, null), 0, 0); default: throw new ArgumentException("kind"); } } /// <summary> /// Creates a token corresponding to a syntax kind. This method can be used for token syntax kinds whose text /// can be inferred by the kind alone. /// </summary> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <returns></returns> public static SyntaxToken Token(SyntaxKind kind) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token corresponding to syntax kind. This method can be used for token syntax kinds whose text can /// be inferred by the kind alone. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, trailing.Node)); } /// <summary> /// Creates a token corresponding to syntax kind. This method gives control over token Text and ValueText. /// /// For example, consider the text '&lt;see cref="operator &amp;#43;"/&gt;'. To create a token for the value of /// the operator symbol (&amp;#43;), one would call /// Token(default(SyntaxTriviaList), SyntaxKind.PlusToken, "&amp;#43;", "+", default(SyntaxTriviaList)). /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="text">The text from which this token was created (e.g. lexed).</param> /// <param name="valueText">How C# should interpret the text of this token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing) { switch (kind) { case SyntaxKind.IdentifierToken: // Have a different representation. throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, nameof(kind)); case SyntaxKind.CharacterLiteralToken: // Value should not have type string. throw new ArgumentException(CSharpResources.UseLiteralForTokens, nameof(kind)); case SyntaxKind.NumericLiteralToken: // Value should not have type string. throw new ArgumentException(CSharpResources.UseLiteralForNumeric, nameof(kind)); } if (!SyntaxFacts.IsAnyToken(kind)) { throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), nameof(kind)); } return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, text, valueText, trailing.Node)); } /// <summary> /// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an /// expected token is not found. A missing token has no text and normally has associated diagnostics. /// </summary> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> public static SyntaxToken MissingToken(SyntaxKind kind) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an /// expected token is not found. A missing token has no text and normally has associated diagnostics. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(leading.Node, kind, trailing.Node)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// </summary> public static SyntaxToken Identifier(string text) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(ElasticMarker.UnderlyingNode, text, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(leading.Node, text, trailing.Node)); } /// <summary> /// Creates a verbatim token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character as it is in source.</param> /// <param name="valueText">The canonical value of the token's text.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing) { if (text.StartsWith("@", StringComparison.Ordinal)) { throw new ArgumentException("text should not start with an @ character."); } return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, leading.Node, "@" + text, valueText, trailing.Node)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="contextualKind">An alternative SyntaxKind that can be inferred for this token in special /// contexts. These are usually keywords.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// <param name="valueText">The text of the identifier name without escapes or leading '@' character.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> /// <returns></returns> public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing) { return new SyntaxToken(InternalSyntax.SyntaxFactory.Identifier(contextualKind, leading.Node, text, valueText, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte signed integer value. /// </summary> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(int value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, int value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte unsigned integer value. /// </summary> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(uint value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, uint value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte signed integer value. /// </summary> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(long value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, long value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte unsigned integer value. /// </summary> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(ulong value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, ulong value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte floating point value. /// </summary> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(float value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, float value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte floating point value. /// </summary> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(double value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, double value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a decimal value. /// </summary> /// <param name="value">The decimal value to be represented by the returned token.</param> public static SyntaxToken Literal(decimal value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The decimal value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, decimal value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The decimal value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind StringLiteralToken from a string value. /// </summary> /// <param name="value">The string value to be represented by the returned token.</param> public static SyntaxToken Literal(string value) { return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value); } /// <summary> /// Creates a token with kind StringLiteralToken from the text and corresponding string value. /// </summary> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The string value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, string value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind StringLiteralToken from the text and corresponding string value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The string value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind CharacterLiteralToken from a character value. /// </summary> /// <param name="value">The character value to be represented by the returned token.</param> public static SyntaxToken Literal(char value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), value); } /// <summary> /// Creates a token with kind CharacterLiteralToken from the text and corresponding character value. /// </summary> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The character value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, char value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind CharacterLiteralToken from the text and corresponding character value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The character value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind BadToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the bad token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.BadToken(leading.Node, text, trailing.Node)); } /// <summary> /// Creates a token with kind XmlTextLiteralToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml text value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind XmlEntityLiteralToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml entity value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlEntity(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates an xml documentation comment that abstracts xml syntax creation. /// </summary> /// <param name="content"> /// A list of xml node syntax that will be the content within the xml documentation comment /// (e.g. a summary element, a returns element, exception element and so on). /// </param> public static DocumentationCommentTriviaSyntax DocumentationComment(params XmlNodeSyntax[] content) { return DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content)) .WithLeadingTrivia(DocumentationCommentExterior("/// ")) .WithTrailingTrivia(EndOfLine("")); } /// <summary> /// Creates a summary element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the summary element.</param> public static XmlElementSyntax XmlSummaryElement(params XmlNodeSyntax[] content) { return XmlSummaryElement(List(content)); } /// <summary> /// Creates a summary element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the summary element.</param> public static XmlElementSyntax XmlSummaryElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.SummaryElementName, content); } /// <summary> /// Creates a see element within an xml documentation comment. /// </summary> /// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param> public static XmlEmptyElementSyntax XmlSeeElement(CrefSyntax cref) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(XmlCrefAttribute(cref)); } /// <summary> /// Creates a seealso element within an xml documentation comment. /// </summary> /// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param> public static XmlEmptyElementSyntax XmlSeeAlsoElement(CrefSyntax cref) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeAlsoElementName).AddAttributes(XmlCrefAttribute(cref)); } /// <summary> /// Creates a seealso element within an xml documentation comment. /// </summary> /// <param name="linkAddress">The uri of the referenced item.</param> /// <param name="linkText">A list of xml node syntax that will be used as the link text for the referenced item.</param> public static XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList<XmlNodeSyntax> linkText) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.SeeAlsoElementName, linkText); return element.WithStartTag(element.StartTag.AddAttributes(XmlTextAttribute(DocumentationCommentXmlNames.CrefAttributeName, linkAddress.ToString()))); } /// <summary> /// Creates a threadsafety element within an xml documentation comment. /// </summary> public static XmlEmptyElementSyntax XmlThreadSafetyElement() { return XmlThreadSafetyElement(true, false); } /// <summary> /// Creates a threadsafety element within an xml documentation comment. /// </summary> /// <param name="isStatic">Indicates whether static member of this type are safe for multi-threaded operations.</param> /// <param name="isInstance">Indicates whether instance members of this type are safe for multi-threaded operations.</param> public static XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance) { return XmlEmptyElement(DocumentationCommentXmlNames.ThreadSafetyElementName).AddAttributes( XmlTextAttribute(DocumentationCommentXmlNames.StaticAttributeName, isStatic.ToString().ToLowerInvariant()), XmlTextAttribute(DocumentationCommentXmlNames.InstanceAttributeName, isInstance.ToString().ToLowerInvariant())); } /// <summary> /// Creates a syntax node for a name attribute in a xml element within a xml documentation comment. /// </summary> /// <param name="parameterName">The value of the name attribute.</param> public static XmlNameAttributeSyntax XmlNameAttribute(string parameterName) { return XmlNameAttribute( XmlName(DocumentationCommentXmlNames.NameAttributeName), Token(SyntaxKind.DoubleQuoteToken), parameterName, Token(SyntaxKind.DoubleQuoteToken)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates a syntax node for a preliminary element within a xml documentation comment. /// </summary> public static XmlEmptyElementSyntax XmlPreliminaryElement() { return XmlEmptyElement(DocumentationCommentXmlNames.PreliminaryElementName); } /// <summary> /// Creates a syntax node for a cref attribute within a xml documentation comment. /// </summary> /// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param> public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref) { return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken); } /// <summary> /// Creates a syntax node for a cref attribute within a xml documentation comment. /// </summary> /// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param> /// <param name="quoteKind">The kind of the quote for the referenced item in the cref attribute.</param> public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref, SyntaxKind quoteKind) { cref = cref.ReplaceTokens(cref.DescendantTokens(), XmlReplaceBracketTokens); return XmlCrefAttribute( XmlName(DocumentationCommentXmlNames.CrefAttributeName), Token(quoteKind), cref, Token(quoteKind)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates a remarks element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param> public static XmlElementSyntax XmlRemarksElement(params XmlNodeSyntax[] content) { return XmlRemarksElement(List(content)); } /// <summary> /// Creates a remarks element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param> public static XmlElementSyntax XmlRemarksElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.RemarksElementName, content); } /// <summary> /// Creates a returns element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the returns element.</param> public static XmlElementSyntax XmlReturnsElement(params XmlNodeSyntax[] content) { return XmlReturnsElement(List(content)); } /// <summary> /// Creates a returns element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the returns element.</param> public static XmlElementSyntax XmlReturnsElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.ReturnsElementName, content); } /// <summary> /// Creates the syntax representation of an xml value element (e.g. for xml documentation comments). /// </summary> /// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param> public static XmlElementSyntax XmlValueElement(params XmlNodeSyntax[] content) { return XmlValueElement(List(content)); } /// <summary> /// Creates the syntax representation of an xml value element (e.g. for xml documentation comments). /// </summary> /// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param> public static XmlElementSyntax XmlValueElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.ValueElementName, content); } /// <summary> /// Creates the syntax representation of an exception element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the exception type.</param> /// <param name="content">A list of syntax nodes that represents the content of the exception element.</param> public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, params XmlNodeSyntax[] content) { return XmlExceptionElement(cref, List(content)); } /// <summary> /// Creates the syntax representation of an exception element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the exception type.</param> /// <param name="content">A list of syntax nodes that represents the content of the exception element.</param> public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExceptionElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref))); } /// <summary> /// Creates the syntax representation of a permission element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the permission type.</param> /// <param name="content">A list of syntax nodes that represents the content of the permission element.</param> public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, params XmlNodeSyntax[] content) { return XmlPermissionElement(cref, List(content)); } /// <summary> /// Creates the syntax representation of a permission element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the permission type.</param> /// <param name="content">A list of syntax nodes that represents the content of the permission element.</param> public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.PermissionElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref))); } /// <summary> /// Creates the syntax representation of an example element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the example element.</param> public static XmlElementSyntax XmlExampleElement(params XmlNodeSyntax[] content) { return XmlExampleElement(List(content)); } /// <summary> /// Creates the syntax representation of an example element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the example element.</param> public static XmlElementSyntax XmlExampleElement(SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExampleElementName, content); return element.WithStartTag(element.StartTag); } /// <summary> /// Creates the syntax representation of a para element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the para element.</param> public static XmlElementSyntax XmlParaElement(params XmlNodeSyntax[] content) { return XmlParaElement(List(content)); } /// <summary> /// Creates the syntax representation of a para element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the para element.</param> public static XmlElementSyntax XmlParaElement(SyntaxList<XmlNodeSyntax> content) { return XmlElement(DocumentationCommentXmlNames.ParaElementName, content); } /// <summary> /// Creates the syntax representation of a param element within xml documentation comments (e.g. for /// documentation of method parameters). /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="content">A list of syntax nodes that represents the content of the param element (e.g. /// the description and meaning of the parameter).</param> public static XmlElementSyntax XmlParamElement(string parameterName, params XmlNodeSyntax[] content) { return XmlParamElement(parameterName, List(content)); } /// <summary> /// Creates the syntax representation of a param element within xml documentation comments (e.g. for /// documentation of method parameters). /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="content">A list of syntax nodes that represents the content of the param element (e.g. /// the description and meaning of the parameter).</param> public static XmlElementSyntax XmlParamElement(string parameterName, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ParameterElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlNameAttribute(parameterName))); } /// <summary> /// Creates the syntax representation of a paramref element within xml documentation comments (e.g. for /// referencing particular parameters of a method). /// </summary> /// <param name="parameterName">The name of the referenced parameter.</param> public static XmlEmptyElementSyntax XmlParamRefElement(string parameterName) { return XmlEmptyElement(DocumentationCommentXmlNames.ParameterReferenceElementName).AddAttributes(XmlNameAttribute(parameterName)); } /// <summary> /// Creates the syntax representation of a see element within xml documentation comments, /// that points to the 'null' language keyword. /// </summary> public static XmlEmptyElementSyntax XmlNullKeywordElement() { return XmlKeywordElement("null"); } /// <summary> /// Creates the syntax representation of a see element within xml documentation comments, /// that points to a language keyword. /// </summary> /// <param name="keyword">The language keyword to which the see element points to.</param> private static XmlEmptyElementSyntax XmlKeywordElement(string keyword) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes( XmlTextAttribute(DocumentationCommentXmlNames.LangwordAttributeName, keyword)); } /// <summary> /// Creates the syntax representation of a placeholder element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param> public static XmlElementSyntax XmlPlaceholderElement(params XmlNodeSyntax[] content) { return XmlPlaceholderElement(List(content)); } /// <summary> /// Creates the syntax representation of a placeholder element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param> public static XmlElementSyntax XmlPlaceholderElement(SyntaxList<XmlNodeSyntax> content) { return XmlElement(DocumentationCommentXmlNames.PlaceholderElementName, content); } /// <summary> /// Creates the syntax representation of a named empty xml element within xml documentation comments. /// </summary> /// <param name="localName">The name of the empty xml element.</param> public static XmlEmptyElementSyntax XmlEmptyElement(string localName) { return XmlEmptyElement(XmlName(localName)); } /// <summary> /// Creates the syntax representation of a named xml element within xml documentation comments. /// </summary> /// <param name="localName">The name of the empty xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml element.</param> public static XmlElementSyntax XmlElement(string localName, SyntaxList<XmlNodeSyntax> content) { return XmlElement(XmlName(localName), content); } /// <summary> /// Creates the syntax representation of a named xml element within xml documentation comments. /// </summary> /// <param name="name">The name of the empty xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml element.</param> public static XmlElementSyntax XmlElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content) { return XmlElement( XmlElementStartTag(name), content, XmlElementEndTag(name)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="value">The value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, string value) { return XmlTextAttribute(name, XmlTextLiteral(value)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens) { return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens) { return XmlTextAttribute(XmlName(name), quoteKind, textTokens); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens) { return XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates the syntax representation of an xml element that spans multiple text lines. /// </summary> /// <param name="localName">The name of the xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param> public static XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(XmlName(localName), content); } /// <summary> /// Creates the syntax representation of an xml element that spans multiple text lines. /// </summary> /// <param name="name">The name of the xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param> public static XmlElementSyntax XmlMultiLineElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content) { return XmlElement( XmlElementStartTag(name), content, XmlElementEndTag(name)); } /// <summary> /// Creates the syntax representation of an xml text that contains a newline token with a documentation comment /// exterior trivia at the end (continued documentation comment). /// </summary> /// <param name="text">The raw text within the new line.</param> public static XmlTextSyntax XmlNewLine(string text) { return XmlText(XmlTextNewLine(text)); } /// <summary> /// Creates the syntax representation of an xml newline token with a documentation comment exterior trivia at /// the end (continued documentation comment). /// </summary> /// <param name="text">The raw text within the new line.</param> public static SyntaxToken XmlTextNewLine(string text) { return XmlTextNewLine(text, true); } /// <summary> /// Creates a token with kind XmlTextLiteralNewLineToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml text new line value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken( InternalSyntax.SyntaxFactory.XmlTextNewLine( leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates the syntax representation of an xml newline token for xml documentation comments. /// </summary> /// <param name="text">The raw text within the new line.</param> /// <param name="continueXmlDocumentationComment"> /// If set to true, a documentation comment exterior token will be added to the trailing trivia /// of the new token.</param> public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment) { var token = new SyntaxToken( InternalSyntax.SyntaxFactory.XmlTextNewLine( ElasticMarker.UnderlyingNode, text, text, ElasticMarker.UnderlyingNode)); if (continueXmlDocumentationComment) token = token.WithTrailingTrivia(token.TrailingTrivia.Add(DocumentationCommentExterior("/// "))); return token; } /// <summary> /// Generates the syntax representation of a xml text node (e.g. for xml documentation comments). /// </summary> /// <param name="value">The string literal used as the text of the xml text node.</param> public static XmlTextSyntax XmlText(string value) { return XmlText(XmlTextLiteral(value)); } /// <summary> /// Generates the syntax representation of a xml text node (e.g. for xml documentation comments). /// </summary> /// <param name="textTokens">A list of text tokens used as the text of the xml text node.</param> public static XmlTextSyntax XmlText(params SyntaxToken[] textTokens) { return XmlText(TokenList(textTokens)); } /// <summary> /// Generates the syntax representation of an xml text literal. /// </summary> /// <param name="value">The text used within the xml text literal.</param> public static SyntaxToken XmlTextLiteral(string value) { // TODO: [RobinSedlaczek] It is no compiler hot path here I think. But the contribution guide // states to avoid LINQ (https://github.com/dotnet/roslyn/wiki/Contributing-Code). With // XText we have a reference to System.Xml.Linq. Isn't this rule valid here? string encoded = new XText(value).ToString(); return XmlTextLiteral( TriviaList(), encoded, value, TriviaList()); } /// <summary> /// Generates the syntax representation of an xml text literal. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The text used within the xml text literal.</param> public static SyntaxToken XmlTextLiteral(string text, string value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Helper method that replaces less-than and greater-than characters with brackets. /// </summary> /// <param name="originalToken">The original token that is to be replaced.</param> /// <param name="rewrittenToken">The new rewritten token.</param> /// <returns>Returns the new rewritten token with replaced characters.</returns> private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken) { if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", rewrittenToken.Text, StringComparison.Ordinal)) return Token(rewrittenToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia); if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", rewrittenToken.Text, StringComparison.Ordinal)) return Token(rewrittenToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia); return rewrittenToken; } /// <summary> /// Creates a trivia with kind DocumentationCommentExteriorTrivia. /// </summary> /// <param name="text">The raw text of the literal.</param> public static SyntaxTrivia DocumentationCommentExterior(string text) { return Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text); } /// <summary> /// Creates an empty list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> public static SyntaxList<TNode> List<TNode>() where TNode : SyntaxNode { return default(SyntaxList<TNode>); } /// <summary> /// Creates a singleton list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="node">The single element node.</param> /// <returns></returns> public static SyntaxList<TNode> SingletonList<TNode>(TNode node) where TNode : SyntaxNode { return new SyntaxList<TNode>(node); } /// <summary> /// Creates a list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of element nodes.</param> public static SyntaxList<TNode> List<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode { return new SyntaxList<TNode>(nodes); } /// <summary> /// Creates an empty list of tokens. /// </summary> public static SyntaxTokenList TokenList() { return default(SyntaxTokenList); } /// <summary> /// Creates a singleton list of tokens. /// </summary> /// <param name="token">The single token.</param> public static SyntaxTokenList TokenList(SyntaxToken token) { return new SyntaxTokenList(token); } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens">An array of tokens.</param> public static SyntaxTokenList TokenList(params SyntaxToken[] tokens) { return new SyntaxTokenList(tokens); } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens"></param> /// <returns></returns> public static SyntaxTokenList TokenList(IEnumerable<SyntaxToken> tokens) { return new SyntaxTokenList(tokens); } /// <summary> /// Creates a trivia from a StructuredTriviaSyntax node. /// </summary> public static SyntaxTrivia Trivia(StructuredTriviaSyntax node) { return new SyntaxTrivia(default(SyntaxToken), node.Green, position: 0, index: 0); } /// <summary> /// Creates an empty list of trivia. /// </summary> public static SyntaxTriviaList TriviaList() { return default(SyntaxTriviaList); } /// <summary> /// Creates a singleton list of trivia. /// </summary> /// <param name="trivia">A single trivia.</param> public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia) { return new SyntaxTriviaList(trivia); } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">An array of trivia.</param> public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias) => new SyntaxTriviaList(trivias); /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">A sequence of trivia.</param> public static SyntaxTriviaList TriviaList(IEnumerable<SyntaxTrivia> trivias) => new SyntaxTriviaList(trivias); /// <summary> /// Creates an empty separated list. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>() where TNode : SyntaxNode { return default(SeparatedSyntaxList<TNode>); } /// <summary> /// Creates a singleton separated list. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="node">A single node.</param> public static SeparatedSyntaxList<TNode> SingletonSeparatedList<TNode>(TNode node) where TNode : SyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxNodeOrTokenList(node, index: 0)); } /// <summary> /// Creates a separated list of nodes from a sequence of nodes, synthesizing comma separators in between. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of syntax nodes.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes) where TNode : SyntaxNode { if (nodes == null) { return default(SeparatedSyntaxList<TNode>); } var collection = nodes as ICollection<TNode>; if (collection != null && collection.Count == 0) { return default(SeparatedSyntaxList<TNode>); } using (var enumerator = nodes.GetEnumerator()) { if (!enumerator.MoveNext()) { return default(SeparatedSyntaxList<TNode>); } var firstNode = enumerator.Current; if (!enumerator.MoveNext()) { return SingletonSeparatedList<TNode>(firstNode); } var builder = new SeparatedSyntaxListBuilder<TNode>(collection != null ? collection.Count : 3); builder.Add(firstNode); var commaToken = Token(SyntaxKind.CommaToken); do { builder.AddSeparator(commaToken); builder.Add(enumerator.Current); } while (enumerator.MoveNext()); return builder.ToList(); } } /// <summary> /// Creates a separated list of nodes from a sequence of nodes and a sequence of separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of syntax nodes.</param> /// <param name="separators">A sequence of token to be interleaved between the nodes. The number of tokens must /// be one less than the number of nodes.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes, IEnumerable<SyntaxToken>? separators) where TNode : SyntaxNode { // Interleave the nodes and the separators. The number of separators must be equal to or 1 less than the number of nodes or // an argument exception is thrown. if (nodes != null) { IEnumerator<TNode> enumerator = nodes.GetEnumerator(); SeparatedSyntaxListBuilder<TNode> builder = SeparatedSyntaxListBuilder<TNode>.Create(); if (separators != null) { foreach (SyntaxToken token in separators) { if (!enumerator.MoveNext()) { throw new ArgumentException($"{nameof(nodes)} must not be empty.", nameof(nodes)); } builder.Add(enumerator.Current); builder.AddSeparator(token); } } if (enumerator.MoveNext()) { builder.Add(enumerator.Current); if (enumerator.MoveNext()) { throw new ArgumentException($"{nameof(separators)} must have 1 fewer element than {nameof(nodes)}", nameof(separators)); } } return builder.ToList(); } if (separators != null) { throw new ArgumentException($"When {nameof(nodes)} is null, {nameof(separators)} must also be null.", nameof(separators)); } return default(SeparatedSyntaxList<TNode>); } /// <summary> /// Creates a separated list from a sequence of nodes and tokens, starting with a node and alternating between additional nodes and separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodesAndTokens">A sequence of nodes or tokens, alternating between nodes and separator tokens.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) where TNode : SyntaxNode { return SeparatedList<TNode>(NodeOrTokenList(nodesAndTokens)); } /// <summary> /// Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>, where the list elements start with a node and then alternate between /// additional nodes and separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodesAndTokens">The list of nodes and tokens.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode { if (!HasSeparatedNodeTokenPattern(nodesAndTokens)) { throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence); } if (!NodesAreCorrectType<TNode>(nodesAndTokens)) { throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList); } return new SeparatedSyntaxList<TNode>(nodesAndTokens); } private static bool NodesAreCorrectType<TNode>(SyntaxNodeOrTokenList list) { for (int i = 0, n = list.Count; i < n; i++) { var element = list[i]; if (element.IsNode && !(element.AsNode() is TNode)) { return false; } } return true; } private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list) { for (int i = 0, n = list.Count; i < n; i++) { var element = list[i]; if (element.IsToken == ((i & 1) == 0)) { return false; } } return true; } /// <summary> /// Creates an empty <see cref="SyntaxNodeOrTokenList"/>. /// </summary> public static SyntaxNodeOrTokenList NodeOrTokenList() { return default(SyntaxNodeOrTokenList); } /// <summary> /// Create a <see cref="SyntaxNodeOrTokenList"/> from a sequence of <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodesAndTokens">The sequence of nodes and tokens</param> public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) { return new SyntaxNodeOrTokenList(nodesAndTokens); } /// <summary> /// Create a <see cref="SyntaxNodeOrTokenList"/> from one or more <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodesAndTokens">The nodes and tokens</param> public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens) { return new SyntaxNodeOrTokenList(nodesAndTokens); } /// <summary> /// Creates an IdentifierNameSyntax node. /// </summary> /// <param name="name">The identifier name.</param> public static IdentifierNameSyntax IdentifierName(string name) { return IdentifierName(Identifier(name)); } // direct access to parsing for common grammar areas /// <summary> /// Create a new syntax tree from a syntax node. /// </summary> public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null) { return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, (CSharpParseOptions?)options, path, encoding); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <inheritdoc cref="CSharpSyntaxTree.ParseText(string, CSharpParseOptions?, string, Encoding?, CancellationToken)"/> public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, encoding, cancellationToken); } /// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/> public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, cancellationToken); } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Parse a list of trivia rules for leading trivia. /// </summary> public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0) { return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset); } /// <summary> /// Parse a list of trivia rules for leading trivia. /// </summary> internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions? options, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options)) { return lexer.LexSyntaxLeadingTrivia(); } } /// <summary> /// Parse a list of trivia using the parsing rules for trailing trivia. /// </summary> public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default)) { return lexer.LexSyntaxTrailingTrivia(); } } // TODO: If this becomes a real API, we'll need to add an offset parameter to // match the pattern followed by the other ParseX methods. internal static CrefSyntax? ParseCref(string text) { // NOTE: Conceivably, we could introduce a new code path that directly calls // DocumentationCommentParser.ParseCrefAttributeValue, but that method won't // work unless the lexer makes the appropriate mode transitions. Rather than // introducing a new code path that will have to be kept in sync with other // mode changes distributed throughout Lexer, SyntaxParser, and // DocumentationCommentParser, we'll just wrap the text in some lexable syntax // and then extract the piece we want. string commentText = string.Format(@"/// <see cref=""{0}""/>", text); SyntaxTriviaList leadingTrivia = ParseLeadingTrivia(commentText, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); Debug.Assert(leadingTrivia.Count == 1); SyntaxTrivia trivia = leadingTrivia.First(); DocumentationCommentTriviaSyntax structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!; Debug.Assert(structure.Content.Count == 2); XmlEmptyElementSyntax elementSyntax = (XmlEmptyElementSyntax)structure.Content[1]; Debug.Assert(elementSyntax.Attributes.Count == 1); XmlAttributeSyntax attributeSyntax = (XmlAttributeSyntax)elementSyntax.Attributes[0]; return attributeSyntax.Kind() == SyntaxKind.XmlCrefAttribute ? ((XmlCrefAttributeSyntax)attributeSyntax).Cref : null; } /// <summary> /// Parse a C# language token. /// </summary> /// <param name="text">The text of the token including leading and trailing trivia.</param> /// <param name="offset">Optional offset into text.</param> public static SyntaxToken ParseToken(string text, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default)) { return new SyntaxToken(lexer.Lex(InternalSyntax.LexerMode.Syntax)); } } /// <summary> /// Parse a sequence of C# language tokens. /// </summary> /// <param name="text">The text of all the tokens.</param> /// <param name="initialTokenPosition">An integer to use as the starting position of the first token.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">Parse options.</param> public static IEnumerable<SyntaxToken> ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default)) { var position = initialTokenPosition; while (true) { var token = lexer.Lex(InternalSyntax.LexerMode.Syntax); yield return new SyntaxToken(parent: null, token: token, position: position, index: 0); position += token.FullWidth; if (token.Kind == SyntaxKind.EndOfFileToken) { break; } } } } /// <summary> /// Parse a NameSyntax node using the grammar rule for names. /// </summary> public static NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset)) using (var parser = MakeParser(lexer)) { var node = parser.ParseName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (NameSyntax)node.CreateRed(); } } /// <summary> /// Parse a TypeNameSyntax node using the grammar rule for type names. /// </summary> // Backcompat overload, do not remove [EditorBrowsable(EditorBrowsableState.Never)] public static TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText) { return ParseTypeName(text, offset, options: null, consumeFullText); } /// <summary> /// Parse a TypeNameSyntax node using the grammar rule for type names. /// </summary> public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseTypeName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (TypeSyntax)node.CreateRed(); } } /// <summary> /// Parse an ExpressionSyntax node using the lowest precedence grammar rule for expressions. /// </summary> /// <param name="text">The text of the expression.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseExpression(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ExpressionSyntax)node.CreateRed(); } } /// <summary> /// Parse a StatementSyntaxNode using grammar rule for statements. /// </summary> /// <param name="text">The text of the statement.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseStatement(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (StatementSyntax)node.CreateRed(); } } /// <summary> /// Parse a MemberDeclarationSyntax. This includes all of the kinds of members that could occur in a type declaration. /// If nothing resembling a valid member declaration is found in the input, returns null. /// </summary> /// <param name="text">The text of the declaration.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input following a declaration should be treated as an error</param> public static MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseMemberDeclaration(); if (node == null) { return null; } return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed(); } } /// <summary> /// Parse a CompilationUnitSyntax using the grammar rule for an entire compilation unit (file). To produce a /// SyntaxTree instance, use CSharpSyntaxTree.ParseText instead. /// </summary> /// <param name="text">The text of the compilation unit.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null) { // note that we do not need a "consumeFullText" parameter, because parsing a compilation unit always must // consume input until the end-of-file using (var lexer = MakeLexer(text, offset, options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseCompilationUnit(); return (CompilationUnitSyntax)node.CreateRed(); } } /// <summary> /// Parse a ParameterListSyntax node. /// </summary> /// <param name="text">The text of the parenthesized parameter list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseParenthesizedParameterList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ParameterListSyntax)node.CreateRed(); } } /// <summary> /// Parse a BracketedParameterListSyntax node. /// </summary> /// <param name="text">The text of the bracketed parameter list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseBracketedParameterList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (BracketedParameterListSyntax)node.CreateRed(); } } /// <summary> /// Parse an ArgumentListSyntax node. /// </summary> /// <param name="text">The text of the parenthesized argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseParenthesizedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Parse a BracketedArgumentListSyntax node. /// </summary> /// <param name="text">The text of the bracketed argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseBracketedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (BracketedArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Parse an AttributeArgumentListSyntax node. /// </summary> /// <param name="text">The text of the attribute argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static AttributeArgumentListSyntax ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseAttributeArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (AttributeArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Helper method for wrapping a string in a SourceText. /// </summary> private static SourceText MakeSourceText(string text, int offset) { return SourceText.From(text, Encoding.UTF8).GetSubText(offset); } private static InternalSyntax.Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null) { return new InternalSyntax.Lexer( text: MakeSourceText(text, offset), options: options ?? CSharpParseOptions.Default); } private static InternalSyntax.LanguageParser MakeParser(InternalSyntax.Lexer lexer) { return new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="oldTree">The original tree.</param> /// <param name="newTree">The new tree.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel) { if (oldTree == null && newTree == null) { return true; } if (oldTree == null || newTree == null) { return false; } return SyntaxEquivalence.AreEquivalent(oldTree, newTree, ignoreChildNode: null, topLevel: topLevel); } /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldNode">The old node.</param> /// <param name="newNode">The new node.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel) { return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: null, topLevel: topLevel); } /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldNode">The old node.</param> /// <param name="newNode">The new node.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func<SyntaxKind, bool>? ignoreChildNode = null) { return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: ignoreChildNode, topLevel: false); } /// <summary> /// Determines if two syntax tokens are the same, disregarding trivia differences. /// </summary> /// <param name="oldToken">The old token.</param> /// <param name="newToken">The new token.</param> public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken) { return SyntaxEquivalence.AreEquivalent(oldToken, newToken); } /// <summary> /// Determines if two lists of tokens are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old token list.</param> /// <param name="newList">The new token list.</param> public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList) { return SyntaxEquivalence.AreEquivalent(oldList, newList); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, bool topLevel) where TNode : CSharpSyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, bool topLevel) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); } internal static TypeSyntax? GetStandaloneType(TypeSyntax? node) { if (node != null) { var parent = node.Parent as ExpressionSyntax; if (parent != null && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName)) { switch (parent.Kind()) { case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)parent; if (qualifiedName.Right == node) { return qualifiedName; } break; case SyntaxKind.AliasQualifiedName: var aliasQualifiedName = (AliasQualifiedNameSyntax)parent; if (aliasQualifiedName.Name == node) { return aliasQualifiedName; } break; } } } return node; } /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> public static ExpressionSyntax GetStandaloneExpression(ExpressionSyntax expression) { return SyntaxFactory.GetStandaloneNode(expression) as ExpressionSyntax ?? expression; } /// <summary> /// Gets the containing expression that is actually a language expression (or something that /// GetSymbolInfo can be applied to) and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// Similarly, if the input node is a cref part that is not independently meaningful, then /// the result will be the full cref. Besides an expression, an input that is a NameSyntax /// of a SubpatternSyntax, e.g. in `name: 3` may cause this method to return the enclosing /// SubpatternSyntax. /// </summary> internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node) { if (node == null || !(node is ExpressionSyntax || node is CrefSyntax)) { return node; } switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: case SyntaxKind.ArrayType: case SyntaxKind.NullableType: // Adjustment may be required. break; default: return node; } CSharpSyntaxNode? parent = node.Parent; if (parent == null) { return node; } switch (parent.Kind()) { case SyntaxKind.QualifiedName: if (((QualifiedNameSyntax)parent).Right == node) { return parent; } break; case SyntaxKind.AliasQualifiedName: if (((AliasQualifiedNameSyntax)parent).Name == node) { return parent; } break; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: if (((MemberAccessExpressionSyntax)parent).Name == node) { return parent; } break; case SyntaxKind.MemberBindingExpression: { if (((MemberBindingExpressionSyntax)parent).Name == node) { return parent; } break; } // Only care about name member crefs because the other cref members // are identifier by keywords, not syntax nodes. case SyntaxKind.NameMemberCref: if (((NameMemberCrefSyntax)parent).Name == node) { CSharpSyntaxNode? grandparent = parent.Parent; return grandparent != null && grandparent.Kind() == SyntaxKind.QualifiedCref ? grandparent : parent; } break; case SyntaxKind.QualifiedCref: if (((QualifiedCrefSyntax)parent).Member == node) { return parent; } break; case SyntaxKind.ArrayCreationExpression: if (((ArrayCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.ObjectCreationExpression: if (node.Kind() == SyntaxKind.NullableType && ((ObjectCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.StackAllocArrayCreationExpression: if (((StackAllocArrayCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.NameColon: if (parent.Parent.IsKind(SyntaxKind.Subpattern)) { return parent.Parent; } break; } return node; } /// <summary> /// Given a conditional binding expression, find corresponding conditional access node. /// </summary> internal static ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node) { var currentNode = node; Debug.Assert(currentNode.Kind() == SyntaxKind.MemberBindingExpression || currentNode.Kind() == SyntaxKind.ElementBindingExpression); // In a well formed tree, the corresponding access node should be one of the ancestors // and its "?" token should precede the binding syntax. while (currentNode != null) { currentNode = currentNode.Parent; Debug.Assert(currentNode != null, "binding should be enclosed in a conditional access"); if (currentNode.Kind() == SyntaxKind.ConditionalAccessExpression) { var condAccess = (ConditionalAccessExpressionSyntax)currentNode; if (condAccess.OperatorToken.EndPosition == node.Position) { return condAccess; } } } return null; } /// <summary> /// Converts a generic name expression into one without the generic arguments. /// </summary> /// <param name="expression"></param> /// <returns></returns> public static ExpressionSyntax? GetNonGenericExpression(ExpressionSyntax expression) { if (expression != null) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var max = (MemberAccessExpressionSyntax)expression; if (max.Name.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)max.Name; return SyntaxFactory.BinaryExpression(expression.Kind(), max.Expression, max.OperatorToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)expression; if (qn.Right.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)qn.Right; return SyntaxFactory.QualifiedName(qn.Left, qn.DotToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; case SyntaxKind.AliasQualifiedName: var an = (AliasQualifiedNameSyntax)expression; if (an.Name.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)an.Name; return SyntaxFactory.AliasQualifiedName(an.Alias, an.ColonColonToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; } } return expression; } /// <summary> /// Determines whether the given text is considered a syntactically complete submission. /// Throws <see cref="ArgumentException"/> if the tree was not compiled as an interactive submission. /// </summary> public static bool IsCompleteSubmission(SyntaxTree tree) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } if (tree.Options.Kind != SourceCodeKind.Script) { throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission); } if (!tree.HasCompilationUnitRoot) { return false; } var compilation = (CompilationUnitSyntax)tree.GetRoot(); if (!compilation.HasErrors) { return true; } foreach (var error in compilation.EndOfFileToken.GetDiagnostics()) { switch ((ErrorCode)error.Code) { case ErrorCode.ERR_OpenEndedComment: case ErrorCode.ERR_EndifDirectiveExpected: case ErrorCode.ERR_EndRegionDirectiveExpected: return false; } } var lastNode = compilation.ChildNodes().LastOrDefault(); if (lastNode == null) { return true; } // unterminated multi-line comment: if (lastNode.HasTrailingTrivia && lastNode.ContainsDiagnostics && HasUnterminatedMultiLineComment(lastNode.GetTrailingTrivia())) { return false; } if (lastNode.IsKind(SyntaxKind.IncompleteMember)) { return false; } // All top-level constructs but global statement (i.e. extern alias, using directive, global attribute, and declarations) // should have a closing token (semicolon, closing brace or bracket) to be complete. if (!lastNode.IsKind(SyntaxKind.GlobalStatement)) { var closingToken = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); return !closingToken.IsMissing; } var globalStatement = (GlobalStatementSyntax)lastNode; var token = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); if (token.IsMissing) { // expression statement terminating semicolon might be missing in script code: if (tree.Options.Kind == SourceCodeKind.Regular || !globalStatement.Statement.IsKind(SyntaxKind.ExpressionStatement) || !token.IsKind(SyntaxKind.SemicolonToken)) { return false; } token = token.GetPreviousToken(predicate: SyntaxToken.Any, stepInto: CodeAnalysis.SyntaxTrivia.Any); if (token.IsMissing) { return false; } } foreach (var error in token.GetDiagnostics()) { switch ((ErrorCode)error.Code) { // unterminated character or string literal: case ErrorCode.ERR_NewlineInConst: // unterminated verbatim string literal: case ErrorCode.ERR_UnterminatedStringLit: // unexpected token following a global statement: case ErrorCode.ERR_GlobalDefinitionOrStatementExpected: case ErrorCode.ERR_EOFExpected: return false; } } return true; } private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { if (trivia.ContainsDiagnostics && trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { return true; } } return false; } /// <summary>Creates a new CaseSwitchLabelSyntax instance.</summary> public static CaseSwitchLabelSyntax CaseSwitchLabel(ExpressionSyntax value) { return SyntaxFactory.CaseSwitchLabel(SyntaxFactory.Token(SyntaxKind.CaseKeyword), value, SyntaxFactory.Token(SyntaxKind.ColonToken)); } /// <summary>Creates a new DefaultSwitchLabelSyntax instance.</summary> public static DefaultSwitchLabelSyntax DefaultSwitchLabel() { return SyntaxFactory.DefaultSwitchLabel(SyntaxFactory.Token(SyntaxKind.DefaultKeyword), SyntaxFactory.Token(SyntaxKind.ColonToken)); } /// <summary>Creates a new BlockSyntax instance.</summary> public static BlockSyntax Block(params StatementSyntax[] statements) { return Block(List(statements)); } /// <summary>Creates a new BlockSyntax instance.</summary> public static BlockSyntax Block(IEnumerable<StatementSyntax> statements) { return Block(List(statements)); } public static PropertyDeclarationSyntax PropertyDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList) { return SyntaxFactory.PropertyDeclaration( attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody: null, initializer: null); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, operatorKeyword: operatorKeyword, type: type, parameterList: parameterList, body: body, expressionBody: null, semicolonToken: semicolonToken); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, explicitInterfaceSpecifier: null, operatorKeyword: operatorKeyword, type: type, parameterList: parameterList, body: body, expressionBody: expressionBody, semicolonToken: semicolonToken); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, explicitInterfaceSpecifier: null, type: type, parameterList: parameterList, body: body, expressionBody: expressionBody); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, operatorKeyword: operatorKeyword, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: null, semicolonToken: semicolonToken); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, explicitInterfaceSpecifier: null, operatorKeyword: operatorKeyword, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: expressionBody, semicolonToken: semicolonToken); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, explicitInterfaceSpecifier: null, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: expressionBody); } /// <summary>Creates a new UsingDirectiveSyntax instance.</summary> public static UsingDirectiveSyntax UsingDirective(NameEqualsSyntax alias, NameSyntax name) { return UsingDirective( usingKeyword: Token(SyntaxKind.UsingKeyword), staticKeyword: default(SyntaxToken), alias: alias, name: name, semicolonToken: Token(SyntaxKind.SemicolonToken)); } public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { return UsingDirective(globalKeyword: default(SyntaxToken), usingKeyword, staticKeyword, alias, name, semicolonToken); } /// <summary>Creates a new ClassOrStructConstraintSyntax instance.</summary> public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword) { return ClassOrStructConstraint(kind, classOrStructKeyword, questionToken: default(SyntaxToken)); } // backwards compatibility for extended API public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, BlockSyntax body) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body, expressionBody: null); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax body, SyntaxToken semicolonToken) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, expressionBody: null, semicolonToken); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body: null, expressionBody); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body: null, expressionBody, semicolonToken); public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue) => EnumMemberDeclaration(attributeLists, modifiers: default, identifier, equalsValue); public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members) => NamespaceDeclaration(attributeLists: default, modifiers: default, name, externs, usings, members); public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) => NamespaceDeclaration(attributeLists: default, modifiers: default, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); /// <summary>Creates a new EventDeclarationSyntax instance.</summary> public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList) { return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken: default); } /// <summary>Creates a new EventDeclarationSyntax instance.</summary> public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken) { return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList: null, semicolonToken); } /// <summary>Creates a new SwitchStatementSyntax instance.</summary> public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression, SyntaxList<SwitchSectionSyntax> sections) { bool needsParens = !(expression is TupleExpressionSyntax); var openParen = needsParens ? SyntaxFactory.Token(SyntaxKind.OpenParenToken) : default; var closeParen = needsParens ? SyntaxFactory.Token(SyntaxKind.CloseParenToken) : default; return SyntaxFactory.SwitchStatement( attributeLists: default, SyntaxFactory.Token(SyntaxKind.SwitchKeyword), openParen, expression, closeParen, SyntaxFactory.Token(SyntaxKind.OpenBraceToken), sections, SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } /// <summary>Creates a new SwitchStatementSyntax instance.</summary> public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression) { return SyntaxFactory.SwitchStatement(expression, default(SyntaxList<SwitchSectionSyntax>)); } public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, CSharpSyntaxNode body) => body is BlockSyntax block ? SimpleLambdaExpression(parameter, block, null) : SimpleLambdaExpression(parameter, null, (ExpressionSyntax)body); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null) : SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body) => ParenthesizedLambdaExpression(ParameterList(), body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? ParenthesizedLambdaExpression(parameterList, block, null) : ParenthesizedLambdaExpression(parameterList, null, (ExpressionSyntax)body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null) : ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body) => AnonymousMethodExpression(parameterList: null, body); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax? parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? AnonymousMethodExpression(default(SyntaxTokenList), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), parameterList, block, null) : throw new ArgumentException(nameof(body)); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null) : throw new ArgumentException(nameof(body)); // BACK COMPAT OVERLOAD DO NOT MODIFY [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] [EditorBrowsable(EditorBrowsableState.Never)] public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) { return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] [EditorBrowsable(EditorBrowsableState.Never)] public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A class containing factory methods for constructing syntax nodes, tokens and trivia. /// </summary> public static partial class SyntaxFactory { /// <summary> /// A trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters. /// </summary> public static SyntaxTrivia CarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed; /// <summary> /// A trivia with kind EndOfLineTrivia containing a single line feed character. /// </summary> public static SyntaxTrivia LineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.LineFeed; /// <summary> /// A trivia with kind EndOfLineTrivia containing a single carriage return character. /// </summary> public static SyntaxTrivia CarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturn; /// <summary> /// A trivia with kind WhitespaceTrivia containing a single space character. /// </summary> public static SyntaxTrivia Space { get; } = Syntax.InternalSyntax.SyntaxFactory.Space; /// <summary> /// A trivia with kind WhitespaceTrivia containing a single tab character. /// </summary> public static SyntaxTrivia Tab { get; } = Syntax.InternalSyntax.SyntaxFactory.Tab; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters. /// Elastic trivia are used to denote trivia that was not produced by parsing source text, and are usually not /// preserved during formatting. /// </summary> public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing a single line feed character. Elastic trivia are used /// to denote trivia that was not produced by parsing source text, and are usually not preserved during /// formatting. /// </summary> public static SyntaxTrivia ElasticLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed; /// <summary> /// An elastic trivia with kind EndOfLineTrivia containing a single carriage return character. Elastic trivia /// are used to denote trivia that was not produced by parsing source text, and are usually not preserved during /// formatting. /// </summary> public static SyntaxTrivia ElasticCarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing a single space character. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> public static SyntaxTrivia ElasticSpace { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticSpace; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing a single tab character. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> public static SyntaxTrivia ElasticTab { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticTab; /// <summary> /// An elastic trivia with kind WhitespaceTrivia containing no characters. Elastic marker trivia are included /// automatically by factory methods when trivia is not specified. Syntax formatting will replace elastic /// markers with appropriate trivia. /// </summary> public static SyntaxTrivia ElasticMarker { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace; /// <summary> /// Creates a trivia with kind EndOfLineTrivia containing the specified text. /// </summary> /// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and /// line feed characters are recognized by the parser as end of line.</param> public static SyntaxTrivia EndOfLine(string text) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: false); } /// <summary> /// Creates a trivia with kind EndOfLineTrivia containing the specified text. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> /// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and /// line feed characters are recognized by the parser as end of line.</param> public static SyntaxTrivia ElasticEndOfLine(string text) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true); } [Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SyntaxTrivia EndOfLine(string text, bool elastic) { return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic); } /// <summary> /// Creates a trivia with kind WhitespaceTrivia containing the specified text. /// </summary> /// <param name="text">The text of the whitespace. Any text can be specified here, however only specific /// whitespace characters are recognized by the parser.</param> public static SyntaxTrivia Whitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false); } /// <summary> /// Creates a trivia with kind WhitespaceTrivia containing the specified text. Elastic trivia are used to /// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting. /// </summary> /// <param name="text">The text of the whitespace. Any text can be specified here, however only specific /// whitespace characters are recognized by the parser.</param> public static SyntaxTrivia ElasticWhitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false); } [Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SyntaxTrivia Whitespace(string text, bool elastic) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic); } /// <summary> /// Creates a trivia with kind either SingleLineCommentTrivia or MultiLineCommentTrivia containing the specified /// text. /// </summary> /// <param name="text">The entire text of the comment including the leading '//' token for single line comments /// or stop or start tokens for multiline comments.</param> public static SyntaxTrivia Comment(string text) { return Syntax.InternalSyntax.SyntaxFactory.Comment(text); } /// <summary> /// Creates a trivia with kind DisabledTextTrivia. Disabled text corresponds to any text between directives that /// is not considered active. /// </summary> public static SyntaxTrivia DisabledText(string text) { return Syntax.InternalSyntax.SyntaxFactory.DisabledText(text); } /// <summary> /// Creates a trivia with kind PreprocessingMessageTrivia. /// </summary> public static SyntaxTrivia PreprocessingMessage(string text) { return Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text); } /// <summary> /// Trivia nodes represent parts of the program text that are not parts of the /// syntactic grammar, such as spaces, newlines, comments, preprocessor /// directives, and disabled code. /// </summary> /// <param name="kind"> /// A <see cref="SyntaxKind"/> representing the specific kind of <see cref="SyntaxTrivia"/>. One of /// <see cref="SyntaxKind.WhitespaceTrivia"/>, <see cref="SyntaxKind.EndOfLineTrivia"/>, /// <see cref="SyntaxKind.SingleLineCommentTrivia"/>, <see cref="SyntaxKind.MultiLineCommentTrivia"/>, /// <see cref="SyntaxKind.DocumentationCommentExteriorTrivia"/>, <see cref="SyntaxKind.DisabledTextTrivia"/> /// </param> /// <param name="text"> /// The actual text of this token. /// </param> public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text) { if (text == null) { throw new ArgumentNullException(nameof(text)); } switch (kind) { case SyntaxKind.DisabledTextTrivia: case SyntaxKind.DocumentationCommentExteriorTrivia: case SyntaxKind.EndOfLineTrivia: case SyntaxKind.MultiLineCommentTrivia: case SyntaxKind.SingleLineCommentTrivia: case SyntaxKind.WhitespaceTrivia: return new SyntaxTrivia(default(SyntaxToken), new Syntax.InternalSyntax.SyntaxTrivia(kind, text, null, null), 0, 0); default: throw new ArgumentException("kind"); } } /// <summary> /// Creates a token corresponding to a syntax kind. This method can be used for token syntax kinds whose text /// can be inferred by the kind alone. /// </summary> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <returns></returns> public static SyntaxToken Token(SyntaxKind kind) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token corresponding to syntax kind. This method can be used for token syntax kinds whose text can /// be inferred by the kind alone. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, trailing.Node)); } /// <summary> /// Creates a token corresponding to syntax kind. This method gives control over token Text and ValueText. /// /// For example, consider the text '&lt;see cref="operator &amp;#43;"/&gt;'. To create a token for the value of /// the operator symbol (&amp;#43;), one would call /// Token(default(SyntaxTriviaList), SyntaxKind.PlusToken, "&amp;#43;", "+", default(SyntaxTriviaList)). /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="text">The text from which this token was created (e.g. lexed).</param> /// <param name="valueText">How C# should interpret the text of this token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing) { switch (kind) { case SyntaxKind.IdentifierToken: // Have a different representation. throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, nameof(kind)); case SyntaxKind.CharacterLiteralToken: // Value should not have type string. throw new ArgumentException(CSharpResources.UseLiteralForTokens, nameof(kind)); case SyntaxKind.NumericLiteralToken: // Value should not have type string. throw new ArgumentException(CSharpResources.UseLiteralForNumeric, nameof(kind)); } if (!SyntaxFacts.IsAnyToken(kind)) { throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), nameof(kind)); } return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, text, valueText, trailing.Node)); } /// <summary> /// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an /// expected token is not found. A missing token has no text and normally has associated diagnostics. /// </summary> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> public static SyntaxToken MissingToken(SyntaxKind kind) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an /// expected token is not found. A missing token has no text and normally has associated diagnostics. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(leading.Node, kind, trailing.Node)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// </summary> public static SyntaxToken Identifier(string text) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(ElasticMarker.UnderlyingNode, text, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(leading.Node, text, trailing.Node)); } /// <summary> /// Creates a verbatim token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character as it is in source.</param> /// <param name="valueText">The canonical value of the token's text.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing) { if (text.StartsWith("@", StringComparison.Ordinal)) { throw new ArgumentException("text should not start with an @ character."); } return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, leading.Node, "@" + text, valueText, trailing.Node)); } /// <summary> /// Creates a token with kind IdentifierToken containing the specified text. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="contextualKind">An alternative SyntaxKind that can be inferred for this token in special /// contexts. These are usually keywords.</param> /// <param name="text">The raw text of the identifier name, including any escapes or leading '@' /// character.</param> /// <param name="valueText">The text of the identifier name without escapes or leading '@' character.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> /// <returns></returns> public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing) { return new SyntaxToken(InternalSyntax.SyntaxFactory.Identifier(contextualKind, leading.Node, text, valueText, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte signed integer value. /// </summary> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(int value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, int value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte unsigned integer value. /// </summary> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(uint value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, uint value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte signed integer value. /// </summary> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(long value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, long value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte unsigned integer value. /// </summary> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(ulong value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, ulong value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a 4-byte floating point value. /// </summary> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(float value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, float value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 4-byte floating point value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from an 8-byte floating point value. /// </summary> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(double value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, double value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The 8-byte floating point value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind NumericLiteralToken from a decimal value. /// </summary> /// <param name="value">The decimal value to be represented by the returned token.</param> public static SyntaxToken Literal(decimal value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The decimal value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, decimal value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The decimal value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind StringLiteralToken from a string value. /// </summary> /// <param name="value">The string value to be represented by the returned token.</param> public static SyntaxToken Literal(string value) { return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value); } /// <summary> /// Creates a token with kind StringLiteralToken from the text and corresponding string value. /// </summary> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The string value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, string value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind StringLiteralToken from the text and corresponding string value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The string value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind CharacterLiteralToken from a character value. /// </summary> /// <param name="value">The character value to be represented by the returned token.</param> public static SyntaxToken Literal(char value) { return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), value); } /// <summary> /// Creates a token with kind CharacterLiteralToken from the text and corresponding character value. /// </summary> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The character value to be represented by the returned token.</param> public static SyntaxToken Literal(string text, char value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Creates a token with kind CharacterLiteralToken from the text and corresponding character value. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal, including quotes and escape sequences.</param> /// <param name="value">The character value to be represented by the returned token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind BadToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the bad token.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.BadToken(leading.Node, text, trailing.Node)); } /// <summary> /// Creates a token with kind XmlTextLiteralToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml text value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates a token with kind XmlEntityLiteralToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml entity value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlEntity(leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates an xml documentation comment that abstracts xml syntax creation. /// </summary> /// <param name="content"> /// A list of xml node syntax that will be the content within the xml documentation comment /// (e.g. a summary element, a returns element, exception element and so on). /// </param> public static DocumentationCommentTriviaSyntax DocumentationComment(params XmlNodeSyntax[] content) { return DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content)) .WithLeadingTrivia(DocumentationCommentExterior("/// ")) .WithTrailingTrivia(EndOfLine("")); } /// <summary> /// Creates a summary element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the summary element.</param> public static XmlElementSyntax XmlSummaryElement(params XmlNodeSyntax[] content) { return XmlSummaryElement(List(content)); } /// <summary> /// Creates a summary element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the summary element.</param> public static XmlElementSyntax XmlSummaryElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.SummaryElementName, content); } /// <summary> /// Creates a see element within an xml documentation comment. /// </summary> /// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param> public static XmlEmptyElementSyntax XmlSeeElement(CrefSyntax cref) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(XmlCrefAttribute(cref)); } /// <summary> /// Creates a seealso element within an xml documentation comment. /// </summary> /// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param> public static XmlEmptyElementSyntax XmlSeeAlsoElement(CrefSyntax cref) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeAlsoElementName).AddAttributes(XmlCrefAttribute(cref)); } /// <summary> /// Creates a seealso element within an xml documentation comment. /// </summary> /// <param name="linkAddress">The uri of the referenced item.</param> /// <param name="linkText">A list of xml node syntax that will be used as the link text for the referenced item.</param> public static XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList<XmlNodeSyntax> linkText) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.SeeAlsoElementName, linkText); return element.WithStartTag(element.StartTag.AddAttributes(XmlTextAttribute(DocumentationCommentXmlNames.CrefAttributeName, linkAddress.ToString()))); } /// <summary> /// Creates a threadsafety element within an xml documentation comment. /// </summary> public static XmlEmptyElementSyntax XmlThreadSafetyElement() { return XmlThreadSafetyElement(true, false); } /// <summary> /// Creates a threadsafety element within an xml documentation comment. /// </summary> /// <param name="isStatic">Indicates whether static member of this type are safe for multi-threaded operations.</param> /// <param name="isInstance">Indicates whether instance members of this type are safe for multi-threaded operations.</param> public static XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance) { return XmlEmptyElement(DocumentationCommentXmlNames.ThreadSafetyElementName).AddAttributes( XmlTextAttribute(DocumentationCommentXmlNames.StaticAttributeName, isStatic.ToString().ToLowerInvariant()), XmlTextAttribute(DocumentationCommentXmlNames.InstanceAttributeName, isInstance.ToString().ToLowerInvariant())); } /// <summary> /// Creates a syntax node for a name attribute in a xml element within a xml documentation comment. /// </summary> /// <param name="parameterName">The value of the name attribute.</param> public static XmlNameAttributeSyntax XmlNameAttribute(string parameterName) { return XmlNameAttribute( XmlName(DocumentationCommentXmlNames.NameAttributeName), Token(SyntaxKind.DoubleQuoteToken), parameterName, Token(SyntaxKind.DoubleQuoteToken)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates a syntax node for a preliminary element within a xml documentation comment. /// </summary> public static XmlEmptyElementSyntax XmlPreliminaryElement() { return XmlEmptyElement(DocumentationCommentXmlNames.PreliminaryElementName); } /// <summary> /// Creates a syntax node for a cref attribute within a xml documentation comment. /// </summary> /// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param> public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref) { return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken); } /// <summary> /// Creates a syntax node for a cref attribute within a xml documentation comment. /// </summary> /// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param> /// <param name="quoteKind">The kind of the quote for the referenced item in the cref attribute.</param> public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref, SyntaxKind quoteKind) { cref = cref.ReplaceTokens(cref.DescendantTokens(), XmlReplaceBracketTokens); return XmlCrefAttribute( XmlName(DocumentationCommentXmlNames.CrefAttributeName), Token(quoteKind), cref, Token(quoteKind)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates a remarks element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param> public static XmlElementSyntax XmlRemarksElement(params XmlNodeSyntax[] content) { return XmlRemarksElement(List(content)); } /// <summary> /// Creates a remarks element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param> public static XmlElementSyntax XmlRemarksElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.RemarksElementName, content); } /// <summary> /// Creates a returns element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the returns element.</param> public static XmlElementSyntax XmlReturnsElement(params XmlNodeSyntax[] content) { return XmlReturnsElement(List(content)); } /// <summary> /// Creates a returns element within an xml documentation comment. /// </summary> /// <param name="content">A list of xml node syntax that will be the content within the returns element.</param> public static XmlElementSyntax XmlReturnsElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.ReturnsElementName, content); } /// <summary> /// Creates the syntax representation of an xml value element (e.g. for xml documentation comments). /// </summary> /// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param> public static XmlElementSyntax XmlValueElement(params XmlNodeSyntax[] content) { return XmlValueElement(List(content)); } /// <summary> /// Creates the syntax representation of an xml value element (e.g. for xml documentation comments). /// </summary> /// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param> public static XmlElementSyntax XmlValueElement(SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(DocumentationCommentXmlNames.ValueElementName, content); } /// <summary> /// Creates the syntax representation of an exception element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the exception type.</param> /// <param name="content">A list of syntax nodes that represents the content of the exception element.</param> public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, params XmlNodeSyntax[] content) { return XmlExceptionElement(cref, List(content)); } /// <summary> /// Creates the syntax representation of an exception element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the exception type.</param> /// <param name="content">A list of syntax nodes that represents the content of the exception element.</param> public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExceptionElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref))); } /// <summary> /// Creates the syntax representation of a permission element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the permission type.</param> /// <param name="content">A list of syntax nodes that represents the content of the permission element.</param> public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, params XmlNodeSyntax[] content) { return XmlPermissionElement(cref, List(content)); } /// <summary> /// Creates the syntax representation of a permission element within xml documentation comments. /// </summary> /// <param name="cref">Syntax representation of the reference to the permission type.</param> /// <param name="content">A list of syntax nodes that represents the content of the permission element.</param> public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.PermissionElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref))); } /// <summary> /// Creates the syntax representation of an example element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the example element.</param> public static XmlElementSyntax XmlExampleElement(params XmlNodeSyntax[] content) { return XmlExampleElement(List(content)); } /// <summary> /// Creates the syntax representation of an example element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the example element.</param> public static XmlElementSyntax XmlExampleElement(SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExampleElementName, content); return element.WithStartTag(element.StartTag); } /// <summary> /// Creates the syntax representation of a para element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the para element.</param> public static XmlElementSyntax XmlParaElement(params XmlNodeSyntax[] content) { return XmlParaElement(List(content)); } /// <summary> /// Creates the syntax representation of a para element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the para element.</param> public static XmlElementSyntax XmlParaElement(SyntaxList<XmlNodeSyntax> content) { return XmlElement(DocumentationCommentXmlNames.ParaElementName, content); } /// <summary> /// Creates the syntax representation of a param element within xml documentation comments (e.g. for /// documentation of method parameters). /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="content">A list of syntax nodes that represents the content of the param element (e.g. /// the description and meaning of the parameter).</param> public static XmlElementSyntax XmlParamElement(string parameterName, params XmlNodeSyntax[] content) { return XmlParamElement(parameterName, List(content)); } /// <summary> /// Creates the syntax representation of a param element within xml documentation comments (e.g. for /// documentation of method parameters). /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="content">A list of syntax nodes that represents the content of the param element (e.g. /// the description and meaning of the parameter).</param> public static XmlElementSyntax XmlParamElement(string parameterName, SyntaxList<XmlNodeSyntax> content) { XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ParameterElementName, content); return element.WithStartTag(element.StartTag.AddAttributes(XmlNameAttribute(parameterName))); } /// <summary> /// Creates the syntax representation of a paramref element within xml documentation comments (e.g. for /// referencing particular parameters of a method). /// </summary> /// <param name="parameterName">The name of the referenced parameter.</param> public static XmlEmptyElementSyntax XmlParamRefElement(string parameterName) { return XmlEmptyElement(DocumentationCommentXmlNames.ParameterReferenceElementName).AddAttributes(XmlNameAttribute(parameterName)); } /// <summary> /// Creates the syntax representation of a see element within xml documentation comments, /// that points to the 'null' language keyword. /// </summary> public static XmlEmptyElementSyntax XmlNullKeywordElement() { return XmlKeywordElement("null"); } /// <summary> /// Creates the syntax representation of a see element within xml documentation comments, /// that points to a language keyword. /// </summary> /// <param name="keyword">The language keyword to which the see element points to.</param> private static XmlEmptyElementSyntax XmlKeywordElement(string keyword) { return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes( XmlTextAttribute(DocumentationCommentXmlNames.LangwordAttributeName, keyword)); } /// <summary> /// Creates the syntax representation of a placeholder element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param> public static XmlElementSyntax XmlPlaceholderElement(params XmlNodeSyntax[] content) { return XmlPlaceholderElement(List(content)); } /// <summary> /// Creates the syntax representation of a placeholder element within xml documentation comments. /// </summary> /// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param> public static XmlElementSyntax XmlPlaceholderElement(SyntaxList<XmlNodeSyntax> content) { return XmlElement(DocumentationCommentXmlNames.PlaceholderElementName, content); } /// <summary> /// Creates the syntax representation of a named empty xml element within xml documentation comments. /// </summary> /// <param name="localName">The name of the empty xml element.</param> public static XmlEmptyElementSyntax XmlEmptyElement(string localName) { return XmlEmptyElement(XmlName(localName)); } /// <summary> /// Creates the syntax representation of a named xml element within xml documentation comments. /// </summary> /// <param name="localName">The name of the empty xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml element.</param> public static XmlElementSyntax XmlElement(string localName, SyntaxList<XmlNodeSyntax> content) { return XmlElement(XmlName(localName), content); } /// <summary> /// Creates the syntax representation of a named xml element within xml documentation comments. /// </summary> /// <param name="name">The name of the empty xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml element.</param> public static XmlElementSyntax XmlElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content) { return XmlElement( XmlElementStartTag(name), content, XmlElementEndTag(name)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="value">The value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, string value) { return XmlTextAttribute(name, XmlTextLiteral(value)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens) { return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens)); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens) { return XmlTextAttribute(XmlName(name), quoteKind, textTokens); } /// <summary> /// Creates the syntax representation of an xml text attribute. /// </summary> /// <param name="name">The name of the xml text attribute.</param> /// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param> /// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param> public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens) { return XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind)) .WithLeadingTrivia(Whitespace(" ")); } /// <summary> /// Creates the syntax representation of an xml element that spans multiple text lines. /// </summary> /// <param name="localName">The name of the xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param> public static XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList<XmlNodeSyntax> content) { return XmlMultiLineElement(XmlName(localName), content); } /// <summary> /// Creates the syntax representation of an xml element that spans multiple text lines. /// </summary> /// <param name="name">The name of the xml element.</param> /// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param> public static XmlElementSyntax XmlMultiLineElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content) { return XmlElement( XmlElementStartTag(name), content, XmlElementEndTag(name)); } /// <summary> /// Creates the syntax representation of an xml text that contains a newline token with a documentation comment /// exterior trivia at the end (continued documentation comment). /// </summary> /// <param name="text">The raw text within the new line.</param> public static XmlTextSyntax XmlNewLine(string text) { return XmlText(XmlTextNewLine(text)); } /// <summary> /// Creates the syntax representation of an xml newline token with a documentation comment exterior trivia at /// the end (continued documentation comment). /// </summary> /// <param name="text">The raw text within the new line.</param> public static SyntaxToken XmlTextNewLine(string text) { return XmlTextNewLine(text, true); } /// <summary> /// Creates a token with kind XmlTextLiteralNewLineToken. /// </summary> /// <param name="leading">A list of trivia immediately preceding the token.</param> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The xml text new line value.</param> /// <param name="trailing">A list of trivia immediately following the token.</param> public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) { return new SyntaxToken( InternalSyntax.SyntaxFactory.XmlTextNewLine( leading.Node, text, value, trailing.Node)); } /// <summary> /// Creates the syntax representation of an xml newline token for xml documentation comments. /// </summary> /// <param name="text">The raw text within the new line.</param> /// <param name="continueXmlDocumentationComment"> /// If set to true, a documentation comment exterior token will be added to the trailing trivia /// of the new token.</param> public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment) { var token = new SyntaxToken( InternalSyntax.SyntaxFactory.XmlTextNewLine( ElasticMarker.UnderlyingNode, text, text, ElasticMarker.UnderlyingNode)); if (continueXmlDocumentationComment) token = token.WithTrailingTrivia(token.TrailingTrivia.Add(DocumentationCommentExterior("/// "))); return token; } /// <summary> /// Generates the syntax representation of a xml text node (e.g. for xml documentation comments). /// </summary> /// <param name="value">The string literal used as the text of the xml text node.</param> public static XmlTextSyntax XmlText(string value) { return XmlText(XmlTextLiteral(value)); } /// <summary> /// Generates the syntax representation of a xml text node (e.g. for xml documentation comments). /// </summary> /// <param name="textTokens">A list of text tokens used as the text of the xml text node.</param> public static XmlTextSyntax XmlText(params SyntaxToken[] textTokens) { return XmlText(TokenList(textTokens)); } /// <summary> /// Generates the syntax representation of an xml text literal. /// </summary> /// <param name="value">The text used within the xml text literal.</param> public static SyntaxToken XmlTextLiteral(string value) { // TODO: [RobinSedlaczek] It is no compiler hot path here I think. But the contribution guide // states to avoid LINQ (https://github.com/dotnet/roslyn/wiki/Contributing-Code). With // XText we have a reference to System.Xml.Linq. Isn't this rule valid here? string encoded = new XText(value).ToString(); return XmlTextLiteral( TriviaList(), encoded, value, TriviaList()); } /// <summary> /// Generates the syntax representation of an xml text literal. /// </summary> /// <param name="text">The raw text of the literal.</param> /// <param name="value">The text used within the xml text literal.</param> public static SyntaxToken XmlTextLiteral(string text, string value) { return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode)); } /// <summary> /// Helper method that replaces less-than and greater-than characters with brackets. /// </summary> /// <param name="originalToken">The original token that is to be replaced.</param> /// <param name="rewrittenToken">The new rewritten token.</param> /// <returns>Returns the new rewritten token with replaced characters.</returns> private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken) { if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", rewrittenToken.Text, StringComparison.Ordinal)) return Token(rewrittenToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia); if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", rewrittenToken.Text, StringComparison.Ordinal)) return Token(rewrittenToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia); return rewrittenToken; } /// <summary> /// Creates a trivia with kind DocumentationCommentExteriorTrivia. /// </summary> /// <param name="text">The raw text of the literal.</param> public static SyntaxTrivia DocumentationCommentExterior(string text) { return Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text); } /// <summary> /// Creates an empty list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> public static SyntaxList<TNode> List<TNode>() where TNode : SyntaxNode { return default(SyntaxList<TNode>); } /// <summary> /// Creates a singleton list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="node">The single element node.</param> /// <returns></returns> public static SyntaxList<TNode> SingletonList<TNode>(TNode node) where TNode : SyntaxNode { return new SyntaxList<TNode>(node); } /// <summary> /// Creates a list of syntax nodes. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of element nodes.</param> public static SyntaxList<TNode> List<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode { return new SyntaxList<TNode>(nodes); } /// <summary> /// Creates an empty list of tokens. /// </summary> public static SyntaxTokenList TokenList() { return default(SyntaxTokenList); } /// <summary> /// Creates a singleton list of tokens. /// </summary> /// <param name="token">The single token.</param> public static SyntaxTokenList TokenList(SyntaxToken token) { return new SyntaxTokenList(token); } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens">An array of tokens.</param> public static SyntaxTokenList TokenList(params SyntaxToken[] tokens) { return new SyntaxTokenList(tokens); } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens"></param> /// <returns></returns> public static SyntaxTokenList TokenList(IEnumerable<SyntaxToken> tokens) { return new SyntaxTokenList(tokens); } /// <summary> /// Creates a trivia from a StructuredTriviaSyntax node. /// </summary> public static SyntaxTrivia Trivia(StructuredTriviaSyntax node) { return new SyntaxTrivia(default(SyntaxToken), node.Green, position: 0, index: 0); } /// <summary> /// Creates an empty list of trivia. /// </summary> public static SyntaxTriviaList TriviaList() { return default(SyntaxTriviaList); } /// <summary> /// Creates a singleton list of trivia. /// </summary> /// <param name="trivia">A single trivia.</param> public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia) { return new SyntaxTriviaList(trivia); } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">An array of trivia.</param> public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias) => new SyntaxTriviaList(trivias); /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">A sequence of trivia.</param> public static SyntaxTriviaList TriviaList(IEnumerable<SyntaxTrivia> trivias) => new SyntaxTriviaList(trivias); /// <summary> /// Creates an empty separated list. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>() where TNode : SyntaxNode { return default(SeparatedSyntaxList<TNode>); } /// <summary> /// Creates a singleton separated list. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="node">A single node.</param> public static SeparatedSyntaxList<TNode> SingletonSeparatedList<TNode>(TNode node) where TNode : SyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxNodeOrTokenList(node, index: 0)); } /// <summary> /// Creates a separated list of nodes from a sequence of nodes, synthesizing comma separators in between. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of syntax nodes.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes) where TNode : SyntaxNode { if (nodes == null) { return default(SeparatedSyntaxList<TNode>); } var collection = nodes as ICollection<TNode>; if (collection != null && collection.Count == 0) { return default(SeparatedSyntaxList<TNode>); } using (var enumerator = nodes.GetEnumerator()) { if (!enumerator.MoveNext()) { return default(SeparatedSyntaxList<TNode>); } var firstNode = enumerator.Current; if (!enumerator.MoveNext()) { return SingletonSeparatedList<TNode>(firstNode); } var builder = new SeparatedSyntaxListBuilder<TNode>(collection != null ? collection.Count : 3); builder.Add(firstNode); var commaToken = Token(SyntaxKind.CommaToken); do { builder.AddSeparator(commaToken); builder.Add(enumerator.Current); } while (enumerator.MoveNext()); return builder.ToList(); } } /// <summary> /// Creates a separated list of nodes from a sequence of nodes and a sequence of separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodes">A sequence of syntax nodes.</param> /// <param name="separators">A sequence of token to be interleaved between the nodes. The number of tokens must /// be one less than the number of nodes.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes, IEnumerable<SyntaxToken>? separators) where TNode : SyntaxNode { // Interleave the nodes and the separators. The number of separators must be equal to or 1 less than the number of nodes or // an argument exception is thrown. if (nodes != null) { IEnumerator<TNode> enumerator = nodes.GetEnumerator(); SeparatedSyntaxListBuilder<TNode> builder = SeparatedSyntaxListBuilder<TNode>.Create(); if (separators != null) { foreach (SyntaxToken token in separators) { if (!enumerator.MoveNext()) { throw new ArgumentException($"{nameof(nodes)} must not be empty.", nameof(nodes)); } builder.Add(enumerator.Current); builder.AddSeparator(token); } } if (enumerator.MoveNext()) { builder.Add(enumerator.Current); if (enumerator.MoveNext()) { throw new ArgumentException($"{nameof(separators)} must have 1 fewer element than {nameof(nodes)}", nameof(separators)); } } return builder.ToList(); } if (separators != null) { throw new ArgumentException($"When {nameof(nodes)} is null, {nameof(separators)} must also be null.", nameof(separators)); } return default(SeparatedSyntaxList<TNode>); } /// <summary> /// Creates a separated list from a sequence of nodes and tokens, starting with a node and alternating between additional nodes and separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodesAndTokens">A sequence of nodes or tokens, alternating between nodes and separator tokens.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) where TNode : SyntaxNode { return SeparatedList<TNode>(NodeOrTokenList(nodesAndTokens)); } /// <summary> /// Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>, where the list elements start with a node and then alternate between /// additional nodes and separator tokens. /// </summary> /// <typeparam name="TNode">The specific type of the element nodes.</typeparam> /// <param name="nodesAndTokens">The list of nodes and tokens.</param> public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode { if (!HasSeparatedNodeTokenPattern(nodesAndTokens)) { throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence); } if (!NodesAreCorrectType<TNode>(nodesAndTokens)) { throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList); } return new SeparatedSyntaxList<TNode>(nodesAndTokens); } private static bool NodesAreCorrectType<TNode>(SyntaxNodeOrTokenList list) { for (int i = 0, n = list.Count; i < n; i++) { var element = list[i]; if (element.IsNode && !(element.AsNode() is TNode)) { return false; } } return true; } private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list) { for (int i = 0, n = list.Count; i < n; i++) { var element = list[i]; if (element.IsToken == ((i & 1) == 0)) { return false; } } return true; } /// <summary> /// Creates an empty <see cref="SyntaxNodeOrTokenList"/>. /// </summary> public static SyntaxNodeOrTokenList NodeOrTokenList() { return default(SyntaxNodeOrTokenList); } /// <summary> /// Create a <see cref="SyntaxNodeOrTokenList"/> from a sequence of <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodesAndTokens">The sequence of nodes and tokens</param> public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) { return new SyntaxNodeOrTokenList(nodesAndTokens); } /// <summary> /// Create a <see cref="SyntaxNodeOrTokenList"/> from one or more <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodesAndTokens">The nodes and tokens</param> public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens) { return new SyntaxNodeOrTokenList(nodesAndTokens); } /// <summary> /// Creates an IdentifierNameSyntax node. /// </summary> /// <param name="name">The identifier name.</param> public static IdentifierNameSyntax IdentifierName(string name) { return IdentifierName(Identifier(name)); } // direct access to parsing for common grammar areas /// <summary> /// Create a new syntax tree from a syntax node. /// </summary> public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null) { return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, (CSharpParseOptions?)options, path, encoding); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <inheritdoc cref="CSharpSyntaxTree.ParseText(string, CSharpParseOptions?, string, Encoding?, CancellationToken)"/> public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, encoding, cancellationToken); } /// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/> public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, cancellationToken); } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Parse a list of trivia rules for leading trivia. /// </summary> public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0) { return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset); } /// <summary> /// Parse a list of trivia rules for leading trivia. /// </summary> internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions? options, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options)) { return lexer.LexSyntaxLeadingTrivia(); } } /// <summary> /// Parse a list of trivia using the parsing rules for trailing trivia. /// </summary> public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default)) { return lexer.LexSyntaxTrailingTrivia(); } } // TODO: If this becomes a real API, we'll need to add an offset parameter to // match the pattern followed by the other ParseX methods. internal static CrefSyntax? ParseCref(string text) { // NOTE: Conceivably, we could introduce a new code path that directly calls // DocumentationCommentParser.ParseCrefAttributeValue, but that method won't // work unless the lexer makes the appropriate mode transitions. Rather than // introducing a new code path that will have to be kept in sync with other // mode changes distributed throughout Lexer, SyntaxParser, and // DocumentationCommentParser, we'll just wrap the text in some lexable syntax // and then extract the piece we want. string commentText = string.Format(@"/// <see cref=""{0}""/>", text); SyntaxTriviaList leadingTrivia = ParseLeadingTrivia(commentText, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); Debug.Assert(leadingTrivia.Count == 1); SyntaxTrivia trivia = leadingTrivia.First(); DocumentationCommentTriviaSyntax structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!; Debug.Assert(structure.Content.Count == 2); XmlEmptyElementSyntax elementSyntax = (XmlEmptyElementSyntax)structure.Content[1]; Debug.Assert(elementSyntax.Attributes.Count == 1); XmlAttributeSyntax attributeSyntax = (XmlAttributeSyntax)elementSyntax.Attributes[0]; return attributeSyntax.Kind() == SyntaxKind.XmlCrefAttribute ? ((XmlCrefAttributeSyntax)attributeSyntax).Cref : null; } /// <summary> /// Parse a C# language token. /// </summary> /// <param name="text">The text of the token including leading and trailing trivia.</param> /// <param name="offset">Optional offset into text.</param> public static SyntaxToken ParseToken(string text, int offset = 0) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default)) { return new SyntaxToken(lexer.Lex(InternalSyntax.LexerMode.Syntax)); } } /// <summary> /// Parse a sequence of C# language tokens. /// </summary> /// <param name="text">The text of all the tokens.</param> /// <param name="initialTokenPosition">An integer to use as the starting position of the first token.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">Parse options.</param> public static IEnumerable<SyntaxToken> ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null) { using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default)) { var position = initialTokenPosition; while (true) { var token = lexer.Lex(InternalSyntax.LexerMode.Syntax); yield return new SyntaxToken(parent: null, token: token, position: position, index: 0); position += token.FullWidth; if (token.Kind == SyntaxKind.EndOfFileToken) { break; } } } } /// <summary> /// Parse a NameSyntax node using the grammar rule for names. /// </summary> public static NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset)) using (var parser = MakeParser(lexer)) { var node = parser.ParseName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (NameSyntax)node.CreateRed(); } } /// <summary> /// Parse a TypeNameSyntax node using the grammar rule for type names. /// </summary> // Backcompat overload, do not remove [EditorBrowsable(EditorBrowsableState.Never)] public static TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText) { return ParseTypeName(text, offset, options: null, consumeFullText); } /// <summary> /// Parse a TypeNameSyntax node using the grammar rule for type names. /// </summary> public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseTypeName(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (TypeSyntax)node.CreateRed(); } } /// <summary> /// Parse an ExpressionSyntax node using the lowest precedence grammar rule for expressions. /// </summary> /// <param name="text">The text of the expression.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseExpression(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ExpressionSyntax)node.CreateRed(); } } /// <summary> /// Parse a StatementSyntaxNode using grammar rule for statements. /// </summary> /// <param name="text">The text of the statement.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseStatement(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (StatementSyntax)node.CreateRed(); } } /// <summary> /// Parse a MemberDeclarationSyntax. This includes all of the kinds of members that could occur in a type declaration. /// If nothing resembling a valid member declaration is found in the input, returns null. /// </summary> /// <param name="text">The text of the declaration.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input following a declaration should be treated as an error</param> public static MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseMemberDeclaration(); if (node == null) { return null; } return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed(); } } /// <summary> /// Parse a CompilationUnitSyntax using the grammar rule for an entire compilation unit (file). To produce a /// SyntaxTree instance, use CSharpSyntaxTree.ParseText instead. /// </summary> /// <param name="text">The text of the compilation unit.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null) { // note that we do not need a "consumeFullText" parameter, because parsing a compilation unit always must // consume input until the end-of-file using (var lexer = MakeLexer(text, offset, options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseCompilationUnit(); return (CompilationUnitSyntax)node.CreateRed(); } } /// <summary> /// Parse a ParameterListSyntax node. /// </summary> /// <param name="text">The text of the parenthesized parameter list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseParenthesizedParameterList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ParameterListSyntax)node.CreateRed(); } } /// <summary> /// Parse a BracketedParameterListSyntax node. /// </summary> /// <param name="text">The text of the bracketed parameter list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseBracketedParameterList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (BracketedParameterListSyntax)node.CreateRed(); } } /// <summary> /// Parse an ArgumentListSyntax node. /// </summary> /// <param name="text">The text of the parenthesized argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseParenthesizedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (ArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Parse a BracketedArgumentListSyntax node. /// </summary> /// <param name="text">The text of the bracketed argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseBracketedArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (BracketedArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Parse an AttributeArgumentListSyntax node. /// </summary> /// <param name="text">The text of the attribute argument list.</param> /// <param name="offset">Optional offset into text.</param> /// <param name="options">The optional parse options to use. If no options are specified default options are /// used.</param> /// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param> public static AttributeArgumentListSyntax ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) { using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options)) using (var parser = MakeParser(lexer)) { var node = parser.ParseAttributeArgumentList(); if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node); return (AttributeArgumentListSyntax)node.CreateRed(); } } /// <summary> /// Helper method for wrapping a string in a SourceText. /// </summary> private static SourceText MakeSourceText(string text, int offset) { return SourceText.From(text, Encoding.UTF8).GetSubText(offset); } private static InternalSyntax.Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null) { return new InternalSyntax.Lexer( text: MakeSourceText(text, offset), options: options ?? CSharpParseOptions.Default); } private static InternalSyntax.LanguageParser MakeParser(InternalSyntax.Lexer lexer) { return new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="oldTree">The original tree.</param> /// <param name="newTree">The new tree.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel) { if (oldTree == null && newTree == null) { return true; } if (oldTree == null || newTree == null) { return false; } return SyntaxEquivalence.AreEquivalent(oldTree, newTree, ignoreChildNode: null, topLevel: topLevel); } /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldNode">The old node.</param> /// <param name="newNode">The new node.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel) { return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: null, topLevel: topLevel); } /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldNode">The old node.</param> /// <param name="newNode">The new node.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func<SyntaxKind, bool>? ignoreChildNode = null) { return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: ignoreChildNode, topLevel: false); } /// <summary> /// Determines if two syntax tokens are the same, disregarding trivia differences. /// </summary> /// <param name="oldToken">The old token.</param> /// <param name="newToken">The new token.</param> public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken) { return SyntaxEquivalence.AreEquivalent(oldToken, newToken); } /// <summary> /// Determines if two lists of tokens are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old token list.</param> /// <param name="newList">The new token list.</param> public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList) { return SyntaxEquivalence.AreEquivalent(oldList, newList); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, bool topLevel) where TNode : CSharpSyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="topLevel"> /// If true then the nodes are equivalent if the contained nodes and tokens declaring /// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies /// or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, bool topLevel) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); } /// <summary> /// Determines if two lists of syntax nodes are the same, disregarding trivia differences. /// </summary> /// <param name="oldList">The old list.</param> /// <param name="newList">The new list.</param> /// <param name="ignoreChildNode"> /// If specified called for every child syntax node (not token) that is visited during the comparison. /// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded. /// </param> public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null) where TNode : SyntaxNode { return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); } internal static TypeSyntax? GetStandaloneType(TypeSyntax? node) { if (node != null) { var parent = node.Parent as ExpressionSyntax; if (parent != null && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName)) { switch (parent.Kind()) { case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)parent; if (qualifiedName.Right == node) { return qualifiedName; } break; case SyntaxKind.AliasQualifiedName: var aliasQualifiedName = (AliasQualifiedNameSyntax)parent; if (aliasQualifiedName.Name == node) { return aliasQualifiedName; } break; } } } return node; } /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> public static ExpressionSyntax GetStandaloneExpression(ExpressionSyntax expression) { return SyntaxFactory.GetStandaloneNode(expression) as ExpressionSyntax ?? expression; } /// <summary> /// Gets the containing expression that is actually a language expression (or something that /// GetSymbolInfo can be applied to) and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// Similarly, if the input node is a cref part that is not independently meaningful, then /// the result will be the full cref. Besides an expression, an input that is a NameSyntax /// of a SubpatternSyntax, e.g. in `name: 3` may cause this method to return the enclosing /// SubpatternSyntax. /// </summary> internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node) { if (node == null || !(node is ExpressionSyntax || node is CrefSyntax)) { return node; } switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: case SyntaxKind.ArrayType: case SyntaxKind.NullableType: // Adjustment may be required. break; default: return node; } CSharpSyntaxNode? parent = node.Parent; if (parent == null) { return node; } switch (parent.Kind()) { case SyntaxKind.QualifiedName: if (((QualifiedNameSyntax)parent).Right == node) { return parent; } break; case SyntaxKind.AliasQualifiedName: if (((AliasQualifiedNameSyntax)parent).Name == node) { return parent; } break; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: if (((MemberAccessExpressionSyntax)parent).Name == node) { return parent; } break; case SyntaxKind.MemberBindingExpression: { if (((MemberBindingExpressionSyntax)parent).Name == node) { return parent; } break; } // Only care about name member crefs because the other cref members // are identifier by keywords, not syntax nodes. case SyntaxKind.NameMemberCref: if (((NameMemberCrefSyntax)parent).Name == node) { CSharpSyntaxNode? grandparent = parent.Parent; return grandparent != null && grandparent.Kind() == SyntaxKind.QualifiedCref ? grandparent : parent; } break; case SyntaxKind.QualifiedCref: if (((QualifiedCrefSyntax)parent).Member == node) { return parent; } break; case SyntaxKind.ArrayCreationExpression: if (((ArrayCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.ObjectCreationExpression: if (node.Kind() == SyntaxKind.NullableType && ((ObjectCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.StackAllocArrayCreationExpression: if (((StackAllocArrayCreationExpressionSyntax)parent).Type == node) { return parent; } break; case SyntaxKind.NameColon: if (parent.Parent.IsKind(SyntaxKind.Subpattern)) { return parent.Parent; } break; } return node; } /// <summary> /// Given a conditional binding expression, find corresponding conditional access node. /// </summary> internal static ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node) { var currentNode = node; Debug.Assert(currentNode.Kind() == SyntaxKind.MemberBindingExpression || currentNode.Kind() == SyntaxKind.ElementBindingExpression); // In a well formed tree, the corresponding access node should be one of the ancestors // and its "?" token should precede the binding syntax. while (currentNode != null) { currentNode = currentNode.Parent; Debug.Assert(currentNode != null, "binding should be enclosed in a conditional access"); if (currentNode.Kind() == SyntaxKind.ConditionalAccessExpression) { var condAccess = (ConditionalAccessExpressionSyntax)currentNode; if (condAccess.OperatorToken.EndPosition == node.Position) { return condAccess; } } } return null; } /// <summary> /// Converts a generic name expression into one without the generic arguments. /// </summary> /// <param name="expression"></param> /// <returns></returns> public static ExpressionSyntax? GetNonGenericExpression(ExpressionSyntax expression) { if (expression != null) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var max = (MemberAccessExpressionSyntax)expression; if (max.Name.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)max.Name; return SyntaxFactory.BinaryExpression(expression.Kind(), max.Expression, max.OperatorToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)expression; if (qn.Right.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)qn.Right; return SyntaxFactory.QualifiedName(qn.Left, qn.DotToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; case SyntaxKind.AliasQualifiedName: var an = (AliasQualifiedNameSyntax)expression; if (an.Name.Kind() == SyntaxKind.GenericName) { var gn = (GenericNameSyntax)an.Name; return SyntaxFactory.AliasQualifiedName(an.Alias, an.ColonColonToken, SyntaxFactory.IdentifierName(gn.Identifier)); } break; } } return expression; } /// <summary> /// Determines whether the given text is considered a syntactically complete submission. /// Throws <see cref="ArgumentException"/> if the tree was not compiled as an interactive submission. /// </summary> public static bool IsCompleteSubmission(SyntaxTree tree) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } if (tree.Options.Kind != SourceCodeKind.Script) { throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission); } if (!tree.HasCompilationUnitRoot) { return false; } var compilation = (CompilationUnitSyntax)tree.GetRoot(); if (!compilation.HasErrors) { return true; } foreach (var error in compilation.EndOfFileToken.GetDiagnostics()) { switch ((ErrorCode)error.Code) { case ErrorCode.ERR_OpenEndedComment: case ErrorCode.ERR_EndifDirectiveExpected: case ErrorCode.ERR_EndRegionDirectiveExpected: return false; } } var lastNode = compilation.ChildNodes().LastOrDefault(); if (lastNode == null) { return true; } // unterminated multi-line comment: if (lastNode.HasTrailingTrivia && lastNode.ContainsDiagnostics && HasUnterminatedMultiLineComment(lastNode.GetTrailingTrivia())) { return false; } if (lastNode.IsKind(SyntaxKind.IncompleteMember)) { return false; } // All top-level constructs but global statement (i.e. extern alias, using directive, global attribute, and declarations) // should have a closing token (semicolon, closing brace or bracket) to be complete. if (!lastNode.IsKind(SyntaxKind.GlobalStatement)) { var closingToken = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); return !closingToken.IsMissing; } var globalStatement = (GlobalStatementSyntax)lastNode; var token = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); if (token.IsMissing) { // expression statement terminating semicolon might be missing in script code: if (tree.Options.Kind == SourceCodeKind.Regular || !globalStatement.Statement.IsKind(SyntaxKind.ExpressionStatement) || !token.IsKind(SyntaxKind.SemicolonToken)) { return false; } token = token.GetPreviousToken(predicate: SyntaxToken.Any, stepInto: CodeAnalysis.SyntaxTrivia.Any); if (token.IsMissing) { return false; } } foreach (var error in token.GetDiagnostics()) { switch ((ErrorCode)error.Code) { // unterminated character or string literal: case ErrorCode.ERR_NewlineInConst: // unterminated verbatim string literal: case ErrorCode.ERR_UnterminatedStringLit: // unexpected token following a global statement: case ErrorCode.ERR_GlobalDefinitionOrStatementExpected: case ErrorCode.ERR_EOFExpected: return false; } } return true; } private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { if (trivia.ContainsDiagnostics && trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { return true; } } return false; } /// <summary>Creates a new CaseSwitchLabelSyntax instance.</summary> public static CaseSwitchLabelSyntax CaseSwitchLabel(ExpressionSyntax value) { return SyntaxFactory.CaseSwitchLabel(SyntaxFactory.Token(SyntaxKind.CaseKeyword), value, SyntaxFactory.Token(SyntaxKind.ColonToken)); } /// <summary>Creates a new DefaultSwitchLabelSyntax instance.</summary> public static DefaultSwitchLabelSyntax DefaultSwitchLabel() { return SyntaxFactory.DefaultSwitchLabel(SyntaxFactory.Token(SyntaxKind.DefaultKeyword), SyntaxFactory.Token(SyntaxKind.ColonToken)); } /// <summary>Creates a new BlockSyntax instance.</summary> public static BlockSyntax Block(params StatementSyntax[] statements) { return Block(List(statements)); } /// <summary>Creates a new BlockSyntax instance.</summary> public static BlockSyntax Block(IEnumerable<StatementSyntax> statements) { return Block(List(statements)); } public static PropertyDeclarationSyntax PropertyDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList) { return SyntaxFactory.PropertyDeclaration( attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody: null, initializer: null); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, operatorKeyword: operatorKeyword, type: type, parameterList: parameterList, body: body, expressionBody: null, semicolonToken: semicolonToken); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, explicitInterfaceSpecifier: null, operatorKeyword: operatorKeyword, type: type, parameterList: parameterList, body: body, expressionBody: expressionBody, semicolonToken: semicolonToken); } public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody) { return SyntaxFactory.ConversionOperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, implicitOrExplicitKeyword: implicitOrExplicitKeyword, explicitInterfaceSpecifier: null, type: type, parameterList: parameterList, body: body, expressionBody: expressionBody); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, operatorKeyword: operatorKeyword, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: null, semicolonToken: semicolonToken); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, explicitInterfaceSpecifier: null, operatorKeyword: operatorKeyword, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: expressionBody, semicolonToken: semicolonToken); } /// <summary>Creates a new OperatorDeclarationSyntax instance.</summary> public static OperatorDeclarationSyntax OperatorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody) { return SyntaxFactory.OperatorDeclaration( attributeLists: attributeLists, modifiers: modifiers, returnType: returnType, explicitInterfaceSpecifier: null, operatorToken: operatorToken, parameterList: parameterList, body: body, expressionBody: expressionBody); } /// <summary>Creates a new UsingDirectiveSyntax instance.</summary> public static UsingDirectiveSyntax UsingDirective(NameEqualsSyntax alias, NameSyntax name) { return UsingDirective( usingKeyword: Token(SyntaxKind.UsingKeyword), staticKeyword: default(SyntaxToken), alias: alias, name: name, semicolonToken: Token(SyntaxKind.SemicolonToken)); } public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { return UsingDirective(globalKeyword: default(SyntaxToken), usingKeyword, staticKeyword, alias, name, semicolonToken); } /// <summary>Creates a new ClassOrStructConstraintSyntax instance.</summary> public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword) { return ClassOrStructConstraint(kind, classOrStructKeyword, questionToken: default(SyntaxToken)); } // backwards compatibility for extended API public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, BlockSyntax body) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body, expressionBody: null); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax body, SyntaxToken semicolonToken) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, expressionBody: null, semicolonToken); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body: null, expressionBody); public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) => SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body: null, expressionBody, semicolonToken); public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue) => EnumMemberDeclaration(attributeLists, modifiers: default, identifier, equalsValue); public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members) => NamespaceDeclaration(attributeLists: default, modifiers: default, name, externs, usings, members); public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) => NamespaceDeclaration(attributeLists: default, modifiers: default, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); /// <summary>Creates a new EventDeclarationSyntax instance.</summary> public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList) { return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken: default); } /// <summary>Creates a new EventDeclarationSyntax instance.</summary> public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken) { return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList: null, semicolonToken); } /// <summary>Creates a new SwitchStatementSyntax instance.</summary> public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression, SyntaxList<SwitchSectionSyntax> sections) { bool needsParens = !(expression is TupleExpressionSyntax); var openParen = needsParens ? SyntaxFactory.Token(SyntaxKind.OpenParenToken) : default; var closeParen = needsParens ? SyntaxFactory.Token(SyntaxKind.CloseParenToken) : default; return SyntaxFactory.SwitchStatement( attributeLists: default, SyntaxFactory.Token(SyntaxKind.SwitchKeyword), openParen, expression, closeParen, SyntaxFactory.Token(SyntaxKind.OpenBraceToken), sections, SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } /// <summary>Creates a new SwitchStatementSyntax instance.</summary> public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression) { return SyntaxFactory.SwitchStatement(expression, default(SyntaxList<SwitchSectionSyntax>)); } public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, CSharpSyntaxNode body) => body is BlockSyntax block ? SimpleLambdaExpression(parameter, block, null) : SimpleLambdaExpression(parameter, null, (ExpressionSyntax)body); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null) : SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body) => ParenthesizedLambdaExpression(ParameterList(), body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? ParenthesizedLambdaExpression(parameterList, block, null) : ParenthesizedLambdaExpression(parameterList, null, (ExpressionSyntax)body); public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null) : ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body) => AnonymousMethodExpression(parameterList: null, body); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax? parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? AnonymousMethodExpression(default(SyntaxTokenList), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), parameterList, block, null) : throw new ArgumentException(nameof(body)); public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body) => body is BlockSyntax block ? AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null) : throw new ArgumentException(nameof(body)); // BACK COMPAT OVERLOAD DO NOT MODIFY [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] [EditorBrowsable(EditorBrowsableState.Never)] public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) { return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] [EditorBrowsable(EditorBrowsableState.Never)] public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseSyntaxTree( string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // BACK COMPAT OVERLOAD DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseSyntaxTree( SourceText text, ParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { partial class Binder { private BoundExpression BindIsPatternExpression(IsPatternExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expression = BindRValueWithoutTargetType(node.Expression, diagnostics); bool hasErrors = IsOperandErrors(node, ref expression, diagnostics); TypeSymbol? expressionType = expression.Type; if (expressionType is null || expressionType.IsVoidType()) { if (!hasErrors) { // value expected diagnostics.Add(ErrorCode.ERR_BadPatternExpression, node.Expression.Location, expression.Display); hasErrors = true; } expression = BadExpression(expression.Syntax, expression); } Debug.Assert(expression.Type is { }); uint inputValEscape = GetValEscape(expression, LocalScopeDepth); BoundPattern pattern = BindPattern(node.Pattern, expression.Type, inputValEscape, permitDesignations: true, hasErrors, diagnostics, underIsPattern: true); hasErrors |= pattern.HasErrors; return MakeIsPatternExpression( node, expression, pattern, GetSpecialType(SpecialType.System_Boolean, diagnostics, node), hasErrors, diagnostics); } private BoundExpression MakeIsPatternExpression( SyntaxNode node, BoundExpression expression, BoundPattern pattern, TypeSymbol boolType, bool hasErrors, BindingDiagnosticBag diagnostics) { // Note that these labels are for the convenience of the compilation of patterns, and are not necessarily emitted into the lowered code. LabelSymbol whenTrueLabel = new GeneratedLabelSymbol("isPatternSuccess"); LabelSymbol whenFalseLabel = new GeneratedLabelSymbol("isPatternFailure"); bool negated = pattern.IsNegated(out var innerPattern); BoundDecisionDag decisionDag = DecisionDagBuilder.CreateDecisionDagForIsPattern( this.Compilation, pattern.Syntax, expression, innerPattern, whenTrueLabel: whenTrueLabel, whenFalseLabel: whenFalseLabel, diagnostics); if (!hasErrors && getConstantResult(decisionDag, negated, whenTrueLabel, whenFalseLabel) is { } constantResult) { if (!constantResult) { Debug.Assert(expression.Type is object); diagnostics.Add(ErrorCode.ERR_IsPatternImpossible, node.Location, expression.Type); hasErrors = true; } else { switch (pattern) { case BoundConstantPattern _: case BoundITuplePattern _: // these patterns can fail in practice throw ExceptionUtilities.Unreachable; case BoundRelationalPattern _: case BoundTypePattern _: case BoundNegatedPattern _: case BoundBinaryPattern _: Debug.Assert(expression.Type is object); diagnostics.Add(ErrorCode.WRN_IsPatternAlways, node.Location, expression.Type); break; case BoundDiscardPattern _: // we do not give a warning on this because it is an existing scenario, and it should // have been obvious in source that it would always match. break; case BoundDeclarationPattern _: case BoundRecursivePattern _: // We do not give a warning on these because people do this to give a name to a value break; } } } else if (expression.ConstantValue != null) { decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(expression); if (!hasErrors && getConstantResult(decisionDag, negated, whenTrueLabel, whenFalseLabel) is { } simplifiedResult) { if (!simplifiedResult) { diagnostics.Add(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, node.Location); } else { switch (pattern) { case BoundConstantPattern _: diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, node.Location); break; case BoundRelationalPattern _: case BoundTypePattern _: case BoundNegatedPattern _: case BoundBinaryPattern _: case BoundDiscardPattern _: diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, node.Location); break; } } } } // decisionDag, whenTrueLabel, and whenFalseLabel represent the decision DAG for the inner pattern, // after removing any outer 'not's, so consumers will need to compensate for negated patterns. return new BoundIsPatternExpression( node, expression, pattern, negated, decisionDag, whenTrueLabel: whenTrueLabel, whenFalseLabel: whenFalseLabel, boolType, hasErrors); static bool? getConstantResult(BoundDecisionDag decisionDag, bool negated, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { if (!decisionDag.ReachableLabels.Contains(whenTrueLabel)) { return negated; } else if (!decisionDag.ReachableLabels.Contains(whenFalseLabel)) { return !negated; } return null; } } private BoundExpression BindSwitchExpression(SwitchExpressionSyntax node, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(node is { }); Binder? switchBinder = this.GetBinder(node); RoslynDebug.Assert(switchBinder is { }); return switchBinder.BindSwitchExpressionCore(node, switchBinder, diagnostics); } internal virtual BoundExpression BindSwitchExpressionCore( SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(this.Next is { }); return this.Next.BindSwitchExpressionCore(node, originalBinder, diagnostics); } internal BoundPattern BindPattern( PatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern = false) { return node switch { DiscardPatternSyntax p => BindDiscardPattern(p, inputType), DeclarationPatternSyntax p => BindDeclarationPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), ConstantPatternSyntax p => BindConstantPatternWithFallbackToTypePattern(p, inputType, hasErrors, diagnostics), RecursivePatternSyntax p => BindRecursivePattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), VarPatternSyntax p => BindVarPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), ParenthesizedPatternSyntax p => BindPattern(p.Pattern, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics, underIsPattern), BinaryPatternSyntax p => BindBinaryPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), UnaryPatternSyntax p => BindUnaryPattern(p, inputType, inputValEscape, hasErrors, diagnostics, underIsPattern), RelationalPatternSyntax p => BindRelationalPattern(p, inputType, hasErrors, diagnostics), TypePatternSyntax p => BindTypePattern(p, inputType, hasErrors, diagnostics), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } private BoundPattern BindDiscardPattern(DiscardPatternSyntax node, TypeSymbol inputType) { return new BoundDiscardPattern(node, inputType: inputType, narrowedType: inputType); } private BoundPattern BindConstantPatternWithFallbackToTypePattern( ConstantPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { return BindConstantPatternWithFallbackToTypePattern(node, node.Expression, inputType, hasErrors, diagnostics); } internal BoundPattern BindConstantPatternWithFallbackToTypePattern( SyntaxNode node, ExpressionSyntax expression, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { ExpressionSyntax innerExpression = SkipParensAndNullSuppressions(expression); if (innerExpression.Kind() == SyntaxKind.DefaultLiteralExpression) { diagnostics.Add(ErrorCode.ERR_DefaultPattern, innerExpression.Location); hasErrors = true; } var convertedExpression = BindExpressionOrTypeForPattern(inputType, innerExpression, ref hasErrors, diagnostics, out var constantValueOpt, out bool wasExpression); if (wasExpression) { return new BoundConstantPattern( node, convertedExpression, constantValueOpt ?? ConstantValue.Bad, inputType, convertedExpression.Type ?? inputType, hasErrors || constantValueOpt is null); } else { if (!hasErrors) CheckFeatureAvailability(innerExpression, MessageID.IDS_FeatureTypePattern, diagnostics); if (hasSuppression(expression)) { diagnostics.Add(ErrorCode.ERR_IllegalSuppression, expression.Location); hasErrors = true; } var boundType = (BoundTypeExpression)convertedExpression; bool isExplicitNotNullTest = boundType.Type.SpecialType == SpecialType.System_Object; return new BoundTypePattern(node, boundType, isExplicitNotNullTest, inputType, boundType.Type, hasErrors); } static bool hasSuppression(ExpressionSyntax e) { while (true) { switch (e) { case ParenthesizedExpressionSyntax p: e = p.Expression; break; case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression }: return true; default: return false; } } } } private ExpressionSyntax SkipParensAndNullSuppressions(ExpressionSyntax e) { while (true) { switch (e) { case ParenthesizedExpressionSyntax p: e = p.Expression; break; case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression } p: e = p.Operand; break; default: return e; } } } /// <summary> /// Binds the expression for a pattern. Sets <paramref name="wasExpression"/> if it was a type rather than an expression, /// and in that case it returns a <see cref="BoundTypeExpression"/>. /// </summary> private BoundExpression BindExpressionOrTypeForPattern( TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression) { constantValueOpt = null; BoundExpression expression = BindTypeOrRValue(patternExpression, diagnostics); wasExpression = expression.Kind != BoundKind.TypeExpression; if (wasExpression) { return BindExpressionForPatternContinued(expression, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt); } else { Debug.Assert(expression is { Kind: BoundKind.TypeExpression, Type: { } }); hasErrors |= CheckValidPatternType(patternExpression, inputType, expression.Type, diagnostics: diagnostics); return expression; } } /// <summary> /// Binds the expression for an is-type right-hand-side, in case it does not bind as a type. /// </summary> private BoundExpression BindExpressionForPattern( TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression) { constantValueOpt = null; var expression = BindExpression(patternExpression, diagnostics: diagnostics, invoked: false, indexed: false); expression = CheckValue(expression, BindValueKind.RValue, diagnostics); wasExpression = expression.Kind switch { BoundKind.BadExpression => false, BoundKind.TypeExpression => false, _ => true }; return wasExpression ? BindExpressionForPatternContinued(expression, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt) : expression; } private BoundExpression BindExpressionForPatternContinued( BoundExpression expression, TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt) { BoundExpression convertedExpression = ConvertPatternExpression( inputType, patternExpression, expression, out constantValueOpt, hasErrors, diagnostics); ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); if (!convertedExpression.HasErrors && !hasErrors) { if (constantValueOpt == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, patternExpression.Location); hasErrors = true; } else if (inputType.IsPointerType()) { CheckFeatureAvailability(patternExpression, MessageID.IDS_FeatureNullPointerConstantPattern, diagnostics, patternExpression.Location); } } if (convertedExpression.Type is null && constantValueOpt != ConstantValue.Null) { Debug.Assert(hasErrors); convertedExpression = new BoundConversion( convertedExpression.Syntax, convertedExpression, Conversion.NoConversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, constantValueOpt: constantValueOpt, conversionGroupOpt: null, type: CreateErrorType(), hasErrors: true) { WasCompilerGenerated = true }; } return convertedExpression; } internal BoundExpression ConvertPatternExpression( TypeSymbol inputType, CSharpSyntaxNode node, BoundExpression expression, out ConstantValue? constantValue, bool hasErrors, BindingDiagnosticBag diagnostics) { BoundExpression convertedExpression; // If we are pattern-matching against an open type, we do not convert the constant to the type of the input. // This permits us to match a value of type `IComparable<T>` with a pattern of type `int`. if (inputType.ContainsTypeParameter()) { convertedExpression = expression; // If the expression does not have a constant value, an error will be reported in the caller if (!hasErrors && expression.ConstantValue is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (expression.ConstantValue == ConstantValue.Null) { // Pointers are value types, but they can be assigned null, so they can be matched against null. if (inputType.IsNonNullableValueType() && !inputType.IsPointerOrFunctionPointer()) { // We do not permit matching null against a struct type. diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, expression.Syntax.Location, inputType); hasErrors = true; } } else { RoslynDebug.Assert(expression.Type is { }); if (ExpressionOfTypeMatchesPatternType(Conversions, inputType, expression.Type, ref useSiteInfo, out _, operandConstantValue: null) == false) { diagnostics.Add(ErrorCode.ERR_PatternWrongType, expression.Syntax.Location, inputType, expression.Display); hasErrors = true; } } if (!hasErrors) { var requiredVersion = MessageID.IDS_FeatureRecursivePatterns.RequiredVersion(); if (Compilation.LanguageVersion < requiredVersion && !this.Conversions.ClassifyConversionFromExpression(expression, inputType, ref useSiteInfo).IsImplicit) { diagnostics.Add(ErrorCode.ERR_ConstantPatternVsOpenType, expression.Syntax.Location, inputType, expression.Display, new CSharpRequiredLanguageVersion(requiredVersion)); } } diagnostics.Add(node, useSiteInfo); } } else { // This will allow user-defined conversions, even though they're not permitted here. This is acceptable // because the result of a user-defined conversion does not have a ConstantValue. A constant pattern // requires a constant value so we'll report a diagnostic to that effect later. convertedExpression = GenerateConversionForAssignment(inputType, expression, diagnostics); if (convertedExpression.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)convertedExpression; BoundExpression operand = conversion.Operand; if (inputType.IsNullableType() && (convertedExpression.ConstantValue == null || !convertedExpression.ConstantValue.IsNull)) { // Null is a special case here because we want to compare null to the Nullable<T> itself, not to the underlying type. // We are not interested in the diagnostic that get created here convertedExpression = CreateConversion(operand, inputType.GetNullableUnderlyingType(), BindingDiagnosticBag.Discarded); } else if ((conversion.ConversionKind == ConversionKind.Boxing || conversion.ConversionKind == ConversionKind.ImplicitReference) && operand.ConstantValue != null && convertedExpression.ConstantValue == null) { // A boxed constant (or string converted to object) is a special case because we prefer // to compare to the pre-converted value by casting the input value to the type of the constant // (that is, unboxing or downcasting it) and then testing the resulting value using primitives. // That is much more efficient than calling object.Equals(x, y), and we can share the downcasted // input value among many constant tests. convertedExpression = operand; } else if (conversion.ConversionKind == ConversionKind.ImplicitNullToPointer || (conversion.ConversionKind == ConversionKind.NoConversion && convertedExpression.Type?.IsErrorType() == true)) { convertedExpression = operand; } } } constantValue = convertedExpression.ConstantValue; return convertedExpression; } /// <summary> /// Check that the pattern type is valid for the operand. Return true if an error was reported. /// </summary> private bool CheckValidPatternType( SyntaxNode typeSyntax, TypeSymbol inputType, TypeSymbol patternType, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert((object)inputType != null); RoslynDebug.Assert((object)patternType != null); if (inputType.IsErrorType() || patternType.IsErrorType()) { return false; } else if (inputType.IsPointerOrFunctionPointer() || patternType.IsPointerOrFunctionPointer()) { // pattern-matching is not permitted for pointer types diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, typeSyntax.Location); return true; } else if (patternType.IsNullableType()) { // It is an error to use pattern-matching with a nullable type, because you'll never get null. Use the underlying type. Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType.GetNullableUnderlyingType()); return true; } else if (typeSyntax is NullableTypeSyntax) { Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType); return true; } else if (patternType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, patternType); return true; } else { if (patternType.IsDynamic()) { Error(diagnostics, ErrorCode.ERR_PatternDynamicType, typeSyntax); return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool? matchPossible = ExpressionOfTypeMatchesPatternType( Conversions, inputType, patternType, ref useSiteInfo, out Conversion conversion, operandConstantValue: null, operandCouldBeNull: true); diagnostics.Add(typeSyntax, useSiteInfo); if (matchPossible != false) { if (!conversion.Exists && (inputType.ContainsTypeParameter() || patternType.ContainsTypeParameter())) { // permit pattern-matching when one of the types is an open type in C# 7.1. LanguageVersion requiredVersion = MessageID.IDS_FeatureGenericPatternMatching.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { Error(diagnostics, ErrorCode.ERR_PatternWrongGenericTypeInVersion, typeSyntax, inputType, patternType, Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); return true; } } } else { Error(diagnostics, ErrorCode.ERR_PatternWrongType, typeSyntax, inputType, patternType); return true; } } return false; } /// <summary> /// Does an expression of type <paramref name="expressionType"/> "match" a pattern that looks for /// type <paramref name="patternType"/>? /// 'true' if the matched type catches all of them, 'false' if it catches none of them, and /// 'null' if it might catch some of them. /// </summary> internal static bool? ExpressionOfTypeMatchesPatternType( Conversions conversions, TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Conversion conversion, ConstantValue? operandConstantValue = null, bool operandCouldBeNull = false) { RoslynDebug.Assert((object)expressionType != null); // Short-circuit a common case. This also improves recovery for some error // cases, e.g. when the type is void. if (expressionType.Equals(patternType, TypeCompareKind.AllIgnoreOptions)) { conversion = Conversion.Identity; return true; } if (expressionType.IsDynamic()) { // if operand is the dynamic type, we do the same thing as though it were object expressionType = conversions.CorLibrary.GetSpecialType(SpecialType.System_Object); } conversion = conversions.ClassifyBuiltInConversion(expressionType, patternType, ref useSiteInfo); ConstantValue result = Binder.GetIsOperatorConstantResult(expressionType, patternType, conversion.Kind, operandConstantValue, operandCouldBeNull); return (result == null) ? (bool?)null : (result == ConstantValue.True) ? true : (result == ConstantValue.False) ? false : throw ExceptionUtilities.UnexpectedValue(result); } private BoundPattern BindDeclarationPattern( DeclarationPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; BoundTypeExpression boundDeclType = BindTypeForPattern(typeSyntax, inputType, diagnostics, ref hasErrors); var valEscape = GetValEscape(boundDeclType.Type, inputValEscape); BindPatternDesignation( designation: node.Designation, declType: boundDeclType.TypeWithAnnotations, valEscape, permitDesignations, typeSyntax, diagnostics, hasErrors: ref hasErrors, variableSymbol: out Symbol? variableSymbol, variableAccess: out BoundExpression? variableAccess); return new BoundDeclarationPattern(node, variableSymbol, variableAccess, boundDeclType, isVar: false, inputType, boundDeclType.Type, hasErrors); } private BoundTypeExpression BindTypeForPattern( TypeSyntax typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors) { RoslynDebug.Assert(inputType is { }); TypeWithAnnotations declType = BindType(typeSyntax, diagnostics, out AliasSymbol aliasOpt); Debug.Assert(declType.HasType); BoundTypeExpression boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, typeWithAnnotations: declType); hasErrors |= CheckValidPatternType(typeSyntax, inputType, declType.Type, diagnostics: diagnostics); return boundDeclType; } private void BindPatternDesignation( VariableDesignationSyntax? designation, TypeWithAnnotations declType, uint inputValEscape, bool permitDesignations, TypeSyntax? typeSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors, out Symbol? variableSymbol, out BoundExpression? variableAccess) { switch (designation) { case SingleVariableDesignationSyntax singleVariableDesignation: SyntaxToken identifier = singleVariableDesignation.Identifier; SourceLocalSymbol localSymbol = this.LookupLocal(identifier); if (!permitDesignations && !identifier.IsMissing) diagnostics.Add(ErrorCode.ERR_DesignatorBeneathPatternCombinator, identifier.GetLocation()); if (localSymbol is { }) { RoslynDebug.Assert(ContainingMemberOrLambda is { }); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) CheckFeatureAvailability(designation, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); localSymbol.SetTypeWithAnnotations(declType); localSymbol.SetValEscape(GetValEscape(declType.Type, inputValEscape)); // Check for variable declaration errors. hasErrors |= localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (!hasErrors) hasErrors = CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax ?? (SyntaxNode)designation); variableSymbol = localSymbol; variableAccess = new BoundLocal( syntax: designation, localSymbol: localSymbol, localSymbol.IsVar ? BoundLocalDeclarationKind.WithInferredType : BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); return; } else { // We should have the right binder in the chain for a script or interactive, so we use the field for the pattern. Debug.Assert(designation.SyntaxTree.Options.Kind != SourceCodeKind.Regular); GlobalExpressionVariable expressionVariableField = LookupDeclaredField(singleVariableDesignation); expressionVariableField.SetTypeWithAnnotations(declType, BindingDiagnosticBag.Discarded); BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); variableSymbol = expressionVariableField; variableAccess = new BoundFieldAccess( syntax: designation, receiver: receiver, fieldSymbol: expressionVariableField, constantValueOpt: null, hasErrors: hasErrors); return; } case DiscardDesignationSyntax _: case null: variableSymbol = null; variableAccess = null; return; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } /// <summary> /// Compute the val escape of an expression of the given <paramref name="type"/>, which is known to be derived /// from an expression whose escape scope is <paramref name="possibleValEscape"/>. By the language rules, the /// result is either that same scope (if the type is a ref struct type) or <see cref="Binder.ExternalScope"/>. /// </summary> private static uint GetValEscape(TypeSymbol type, uint possibleValEscape) { return type.IsRefLikeType ? possibleValEscape : Binder.ExternalScope; } private TypeWithAnnotations BindRecursivePatternType( TypeSyntax? typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors, out BoundTypeExpression? boundDeclType) { if (typeSyntax != null) { boundDeclType = BindTypeForPattern(typeSyntax, inputType, diagnostics, ref hasErrors); return boundDeclType.TypeWithAnnotations; } else { boundDeclType = null; // remove the nullable part of the input's type; e.g. a nullable int becomes an int in a recursive pattern return TypeWithAnnotations.Create(inputType.StrippedType(), NullableAnnotation.NotAnnotated); } } // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this code and its callers. internal static bool IsZeroElementTupleType(TypeSymbol type) { return type.IsStructType() && type.Name == "ValueTuple" && type.GetArity() == 0 && type.ContainingSymbol is var declContainer && declContainer.Kind == SymbolKind.Namespace && declContainer.Name == "System" && (declContainer.ContainingSymbol as NamespaceSymbol)?.IsGlobalNamespace == true; } private BoundPattern BindRecursivePattern( RecursivePatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { if (inputType.IsPointerOrFunctionPointer()) { diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, node.Location); hasErrors = true; inputType = CreateErrorType(); } TypeSyntax? typeSyntax = node.Type; TypeWithAnnotations declTypeWithAnnotations = BindRecursivePatternType(typeSyntax, inputType, diagnostics, ref hasErrors, out BoundTypeExpression? boundDeclType); TypeSymbol declType = declTypeWithAnnotations.Type; inputValEscape = GetValEscape(declType, inputValEscape); MethodSymbol? deconstructMethod = null; ImmutableArray<BoundPositionalSubpattern> deconstructionSubpatterns = default; if (node.PositionalPatternClause != null) { PositionalPatternClauseSyntax positionalClause = node.PositionalPatternClause; var patternsBuilder = ArrayBuilder<BoundPositionalSubpattern>.GetInstance(positionalClause.Subpatterns.Count); if (IsZeroElementTupleType(declType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. BindValueTupleSubpatterns( positionalClause, declType, ImmutableArray<TypeWithAnnotations>.Empty, inputValEscape, permitDesignations, ref hasErrors, patternsBuilder, diagnostics); } else if (declType.IsTupleType) { // It is a tuple type. Work according to its elements BindValueTupleSubpatterns(positionalClause, declType, declType.TupleElementTypesWithAnnotations, inputValEscape, permitDesignations, ref hasErrors, patternsBuilder, diagnostics); } else { // It is not a tuple type. Seek an appropriate Deconstruct method. var inputPlaceholder = new BoundImplicitReceiver(positionalClause, declType); // A fake receiver expression to permit us to reuse binding logic var deconstructDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); BoundExpression deconstruct = MakeDeconstructInvocationExpression( positionalClause.Subpatterns.Count, inputPlaceholder, positionalClause, deconstructDiagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyDeconstructCandidates); if (!anyDeconstructCandidates && ShouldUseITupleForRecursivePattern(node, declType, diagnostics, out var iTupleType, out var iTupleGetLength, out var iTupleGetItem)) { // There was no Deconstruct, but the constraints for the use of ITuple are satisfied. // Use that and forget any errors from trying to bind Deconstruct. deconstructDiagnostics.Free(); BindITupleSubpatterns(positionalClause, patternsBuilder, permitDesignations, diagnostics); deconstructionSubpatterns = patternsBuilder.ToImmutableAndFree(); return new BoundITuplePattern(node, iTupleGetLength, iTupleGetItem, deconstructionSubpatterns, inputType, iTupleType, hasErrors); } else { diagnostics.AddRangeAndFree(deconstructDiagnostics); } deconstructMethod = BindDeconstructSubpatterns( positionalClause, inputValEscape, permitDesignations, deconstruct, outPlaceholders, patternsBuilder, ref hasErrors, diagnostics); } deconstructionSubpatterns = patternsBuilder.ToImmutableAndFree(); } ImmutableArray<BoundPropertySubpattern> properties = default; if (node.PropertyPatternClause != null) { properties = BindPropertyPatternClause(node.PropertyPatternClause, declType, inputValEscape, permitDesignations, diagnostics, ref hasErrors); } BindPatternDesignation( node.Designation, declTypeWithAnnotations, inputValEscape, permitDesignations, typeSyntax, diagnostics, ref hasErrors, out Symbol? variableSymbol, out BoundExpression? variableAccess); bool isExplicitNotNullTest = node.Designation is null && boundDeclType is null && properties.IsDefaultOrEmpty && deconstructMethod is null && deconstructionSubpatterns.IsDefault; return new BoundRecursivePattern( syntax: node, declaredType: boundDeclType, deconstructMethod: deconstructMethod, deconstruction: deconstructionSubpatterns, properties: properties, variable: variableSymbol, variableAccess: variableAccess, isExplicitNotNullTest: isExplicitNotNullTest, inputType: inputType, narrowedType: boundDeclType?.Type ?? inputType.StrippedType(), hasErrors: hasErrors); } private MethodSymbol? BindDeconstructSubpatterns( PositionalPatternClauseSyntax node, uint inputValEscape, bool permitDesignations, BoundExpression deconstruct, ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, ArrayBuilder<BoundPositionalSubpattern> patterns, ref bool hasErrors, BindingDiagnosticBag diagnostics) { var deconstructMethod = deconstruct.ExpressionSymbol as MethodSymbol; if (deconstructMethod is null) hasErrors = true; int skippedExtensionParameters = deconstructMethod?.IsExtensionMethod == true ? 1 : 0; for (int i = 0; i < node.Subpatterns.Count; i++) { var subPattern = node.Subpatterns[i]; bool isError = hasErrors || outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; TypeSymbol elementType = isError ? CreateErrorType() : outPlaceholders[i].Type; ParameterSymbol? parameter = null; if (!isError) { if (subPattern.NameColon != null) { // Check that the given name is the same as the corresponding parameter of the method. int parameterIndex = i + skippedExtensionParameters; if (parameterIndex < deconstructMethod!.ParameterCount) { parameter = deconstructMethod.Parameters[parameterIndex]; string name = subPattern.NameColon.Name.Identifier.ValueText; string parameterName = parameter.Name; if (name != parameterName) { diagnostics.Add(ErrorCode.ERR_DeconstructParameterNameMismatch, subPattern.NameColon.Name.Location, name, parameterName); } } } else if (subPattern.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subPattern.ExpressionColon.Expression.Location); } } var boundSubpattern = new BoundPositionalSubpattern( subPattern, parameter, BindPattern(subPattern.Pattern, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics) ); patterns.Add(boundSubpattern); } return deconstructMethod; } private void BindITupleSubpatterns( PositionalPatternClauseSyntax node, ArrayBuilder<BoundPositionalSubpattern> patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) { // Since the input has been cast to ITuple, it must be escapable. const uint valEscape = Binder.ExternalScope; var objectType = Compilation.GetSpecialType(SpecialType.System_Object); foreach (var subpatternSyntax in node.Subpatterns) { if (subpatternSyntax.NameColon != null) { // error: name not permitted in ITuple deconstruction diagnostics.Add(ErrorCode.ERR_ArgumentNameInITuplePattern, subpatternSyntax.NameColon.Location); } else if (subpatternSyntax.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subpatternSyntax.ExpressionColon.Expression.Location); } var boundSubpattern = new BoundPositionalSubpattern( subpatternSyntax, null, BindPattern(subpatternSyntax.Pattern, objectType, valEscape, permitDesignations, hasErrors: false, diagnostics)); patterns.Add(boundSubpattern); } } private void BindITupleSubpatterns( ParenthesizedVariableDesignationSyntax node, ArrayBuilder<BoundPositionalSubpattern> patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) { // Since the input has been cast to ITuple, it must be escapable. const uint valEscape = Binder.ExternalScope; var objectType = Compilation.GetSpecialType(SpecialType.System_Object); foreach (var variable in node.Variables) { BoundPattern pattern = BindVarDesignation(variable, objectType, valEscape, permitDesignations, hasErrors: false, diagnostics); var boundSubpattern = new BoundPositionalSubpattern( variable, null, pattern); patterns.Add(boundSubpattern); } } private void BindValueTupleSubpatterns( PositionalPatternClauseSyntax node, TypeSymbol declType, ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations, uint inputValEscape, bool permitDesignations, ref bool hasErrors, ArrayBuilder<BoundPositionalSubpattern> patterns, BindingDiagnosticBag diagnostics) { if (elementTypesWithAnnotations.Length != node.Subpatterns.Count && !hasErrors) { diagnostics.Add(ErrorCode.ERR_WrongNumberOfSubpatterns, node.Location, declType, elementTypesWithAnnotations.Length, node.Subpatterns.Count); hasErrors = true; } for (int i = 0; i < node.Subpatterns.Count; i++) { var subpatternSyntax = node.Subpatterns[i]; bool isError = i >= elementTypesWithAnnotations.Length; TypeSymbol elementType = isError ? CreateErrorType() : elementTypesWithAnnotations[i].Type; FieldSymbol? foundField = null; if (!isError) { if (subpatternSyntax.NameColon != null) { string name = subpatternSyntax.NameColon.Name.Identifier.ValueText; foundField = CheckIsTupleElement(subpatternSyntax.NameColon.Name, (NamedTypeSymbol)declType, name, i, diagnostics); } else if (subpatternSyntax.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subpatternSyntax.ExpressionColon.Expression.Location); } } BoundPositionalSubpattern boundSubpattern = new BoundPositionalSubpattern( subpatternSyntax, foundField, BindPattern(subpatternSyntax.Pattern, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics)); patterns.Add(boundSubpattern); } } private bool ShouldUseITupleForRecursivePattern( RecursivePatternSyntax node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) { iTupleType = null; iTupleGetLength = iTupleGetItem = null; if (node.Type != null) { // ITuple matching only applies if no type is given explicitly. return false; } if (node.PropertyPatternClause != null) { // ITuple matching only applies if there is no property pattern part. return false; } if (node.PositionalPatternClause == null) { // ITuple matching only applies if there is a positional pattern part. // This can only occur as a result of syntax error recovery, if at all. return false; } if (node.Designation?.Kind() == SyntaxKind.SingleVariableDesignation) { // ITuple matching only applies if there is no variable declared (what type would the variable be?) return false; } return ShouldUseITuple(node, declType, diagnostics, out iTupleType, out iTupleGetLength, out iTupleGetItem); } private bool ShouldUseITuple( SyntaxNode node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) { iTupleType = null; iTupleGetLength = iTupleGetItem = null; Debug.Assert(!declType.IsTupleType); Debug.Assert(!IsZeroElementTupleType(declType)); if (Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion()) { return false; } iTupleType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_ITuple); if (iTupleType.TypeKind != TypeKind.Interface) { // When compiling to a platform that lacks the interface ITuple (i.e. it is an error type), we simply do not match using it. return false; } // Resolution 2017-11-20 LDM: permit matching via ITuple only for `object`, `ITuple`, and types that are // declared to implement `ITuple`. if (declType != (object)Compilation.GetSpecialType(SpecialType.System_Object) && declType != (object)Compilation.DynamicType && declType != (object)iTupleType && !hasBaseInterface(declType, iTupleType)) { return false; } // Ensure ITuple has a Length and indexer iTupleGetLength = (MethodSymbol?)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length); iTupleGetItem = (MethodSymbol?)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item); if (iTupleGetLength is null || iTupleGetItem is null) { // This might not result in an ideal diagnostic return false; } // passed all the filters; permit using ITuple _ = diagnostics.ReportUseSite(iTupleType, node) || diagnostics.ReportUseSite(iTupleGetLength, node) || diagnostics.ReportUseSite(iTupleGetItem, node); return true; bool hasBaseInterface(TypeSymbol type, NamedTypeSymbol possibleBaseInterface) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Compilation.Conversions.ClassifyBuiltInConversion(type, possibleBaseInterface, ref useSiteInfo).IsImplicit; diagnostics.Add(node, useSiteInfo); return result; } } /// <summary> /// Check that the given name designates a tuple element at the given index, and return that element. /// </summary> private static FieldSymbol? CheckIsTupleElement(SyntaxNode node, NamedTypeSymbol tupleType, string name, int tupleIndex, BindingDiagnosticBag diagnostics) { FieldSymbol? foundElement = null; foreach (var symbol in tupleType.GetMembers(name)) { if (symbol is FieldSymbol field && field.IsTupleElement()) { foundElement = field; break; } } if (foundElement is null || foundElement.TupleElementIndex != tupleIndex) { diagnostics.Add(ErrorCode.ERR_TupleElementNameMismatch, node.Location, name, $"Item{tupleIndex + 1}"); } return foundElement; } private BoundPattern BindVarPattern( VarPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { if ((inputType.IsPointerOrFunctionPointer() && node.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation) || (inputType.IsPointerType() && Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion())) { diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, node.Location); hasErrors = true; inputType = CreateErrorType(); } Symbol foundSymbol = BindTypeOrAliasOrKeyword(node.VarKeyword, node, diagnostics, out bool isVar).Symbol; if (!isVar) { // Give an error if there is a bindable type "var" in scope diagnostics.Add(ErrorCode.ERR_VarMayNotBindToType, node.VarKeyword.GetLocation(), foundSymbol.ToDisplayString()); hasErrors = true; } return BindVarDesignation(node.Designation, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); } private BoundPattern BindVarDesignation( VariableDesignationSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.DiscardDesignation: { return new BoundDiscardPattern(node, inputType: inputType, narrowedType: inputType); } case SyntaxKind.SingleVariableDesignation: { var declType = TypeWithState.ForType(inputType).ToTypeWithAnnotations(Compilation); BindPatternDesignation( designation: node, declType: declType, inputValEscape: inputValEscape, permitDesignations: permitDesignations, typeSyntax: null, diagnostics: diagnostics, hasErrors: ref hasErrors, variableSymbol: out Symbol? variableSymbol, variableAccess: out BoundExpression? variableAccess); var boundOperandType = new BoundTypeExpression(syntax: node, aliasOpt: null, typeWithAnnotations: declType); // fake a type expression for the variable's type // We continue to use a BoundDeclarationPattern for the var pattern, as they have more in common. Debug.Assert(node.Parent is { }); return new BoundDeclarationPattern( node.Parent.Kind() == SyntaxKind.VarPattern ? node.Parent : node, // for `var x` use whole pattern, otherwise use designation for the syntax variableSymbol, variableAccess, boundOperandType, isVar: true, inputType: inputType, narrowedType: inputType, hasErrors: hasErrors); } case SyntaxKind.ParenthesizedVariableDesignation: { var tupleDesignation = (ParenthesizedVariableDesignationSyntax)node; var subPatterns = ArrayBuilder<BoundPositionalSubpattern>.GetInstance(tupleDesignation.Variables.Count); MethodSymbol? deconstructMethod = null; var strippedInputType = inputType.StrippedType(); if (IsZeroElementTupleType(strippedInputType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. addSubpatternsForTuple(ImmutableArray<TypeWithAnnotations>.Empty); } else if (strippedInputType.IsTupleType) { // It is a tuple type. Work according to its elements addSubpatternsForTuple(strippedInputType.TupleElementTypesWithAnnotations); } else { // It is not a tuple type. Seek an appropriate Deconstruct method. var inputPlaceholder = new BoundImplicitReceiver(node, strippedInputType); // A fake receiver expression to permit us to reuse binding logic var deconstructDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); BoundExpression deconstruct = MakeDeconstructInvocationExpression( tupleDesignation.Variables.Count, inputPlaceholder, node, deconstructDiagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyDeconstructCandidates); if (!anyDeconstructCandidates && ShouldUseITuple(node, strippedInputType, diagnostics, out var iTupleType, out var iTupleGetLength, out var iTupleGetItem)) { // There was no applicable candidate Deconstruct, and the constraints for the use of ITuple are satisfied. // Use that and forget any errors from trying to bind Deconstruct. deconstructDiagnostics.Free(); BindITupleSubpatterns(tupleDesignation, subPatterns, permitDesignations, diagnostics); return new BoundITuplePattern(node, iTupleGetLength, iTupleGetItem, subPatterns.ToImmutableAndFree(), strippedInputType, iTupleType, hasErrors); } else { diagnostics.AddRangeAndFree(deconstructDiagnostics); } deconstructMethod = deconstruct.ExpressionSymbol as MethodSymbol; if (!hasErrors) hasErrors = outPlaceholders.IsDefault || tupleDesignation.Variables.Count != outPlaceholders.Length; for (int i = 0; i < tupleDesignation.Variables.Count; i++) { var variable = tupleDesignation.Variables[i]; bool isError = outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; TypeSymbol elementType = isError ? CreateErrorType() : outPlaceholders[i].Type; BoundPattern pattern = BindVarDesignation(variable, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics); subPatterns.Add(new BoundPositionalSubpattern(variable, symbol: null, pattern)); } } return new BoundRecursivePattern( syntax: node, declaredType: null, deconstructMethod: deconstructMethod, deconstruction: subPatterns.ToImmutableAndFree(), properties: default, variable: null, variableAccess: null, isExplicitNotNullTest: false, inputType: inputType, narrowedType: inputType.StrippedType(), hasErrors: hasErrors); void addSubpatternsForTuple(ImmutableArray<TypeWithAnnotations> elementTypes) { if (elementTypes.Length != tupleDesignation.Variables.Count && !hasErrors) { diagnostics.Add(ErrorCode.ERR_WrongNumberOfSubpatterns, tupleDesignation.Location, strippedInputType, elementTypes.Length, tupleDesignation.Variables.Count); hasErrors = true; } for (int i = 0; i < tupleDesignation.Variables.Count; i++) { var variable = tupleDesignation.Variables[i]; bool isError = i >= elementTypes.Length; TypeSymbol elementType = isError ? CreateErrorType() : elementTypes[i].Type; BoundPattern pattern = BindVarDesignation(variable, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics); subPatterns.Add(new BoundPositionalSubpattern(variable, symbol: null, pattern)); } } } default: { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } } private ImmutableArray<BoundPropertySubpattern> BindPropertyPatternClause( PropertyPatternClauseSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var builder = ArrayBuilder<BoundPropertySubpattern>.GetInstance(node.Subpatterns.Count); foreach (SubpatternSyntax p in node.Subpatterns) { ExpressionSyntax? expr = p.ExpressionColon?.Expression; PatternSyntax pattern = p.Pattern; BoundPropertySubpatternMember? member; TypeSymbol memberType; if (expr == null) { if (!hasErrors) diagnostics.Add(ErrorCode.ERR_PropertyPatternNameMissing, pattern.Location, pattern); memberType = CreateErrorType(); member = null; hasErrors = true; } else { member = LookupMembersForPropertyPattern(inputType, expr, diagnostics, ref hasErrors); memberType = member.Type; } BoundPattern boundPattern = BindPattern(pattern, memberType, GetValEscape(memberType, inputValEscape), permitDesignations, hasErrors, diagnostics); builder.Add(new BoundPropertySubpattern(p, member, boundPattern)); } return builder.ToImmutableAndFree(); } private BoundPropertySubpatternMember LookupMembersForPropertyPattern( TypeSymbol inputType, ExpressionSyntax expr, BindingDiagnosticBag diagnostics, ref bool hasErrors) { BoundPropertySubpatternMember? receiver = null; Symbol? symbol = null; switch (expr) { case IdentifierNameSyntax name: symbol = BindPropertyPatternMember(inputType, name, ref hasErrors, diagnostics); break; case MemberAccessExpressionSyntax { Name: IdentifierNameSyntax name } memberAccess when memberAccess.IsKind(SyntaxKind.SimpleMemberAccessExpression): receiver = LookupMembersForPropertyPattern(inputType, memberAccess.Expression, diagnostics, ref hasErrors); symbol = BindPropertyPatternMember(receiver.Type.StrippedType(), name, ref hasErrors, diagnostics); break; default: Error(diagnostics, ErrorCode.ERR_InvalidNameInSubpattern, expr); hasErrors = true; break; } TypeSymbol memberType = symbol switch { FieldSymbol field => field.Type, PropertySymbol property => property.Type, _ => CreateErrorType() }; return new BoundPropertySubpatternMember(expr, receiver, symbol, type: memberType, hasErrors); } private Symbol? BindPropertyPatternMember( TypeSymbol inputType, IdentifierNameSyntax memberName, ref bool hasErrors, BindingDiagnosticBag diagnostics) { // TODO: consider refactoring out common code with BindObjectInitializerMember BoundImplicitReceiver implicitReceiver = new BoundImplicitReceiver(memberName, inputType); string name = memberName.Identifier.ValueText; BoundExpression boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: name, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess( (BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); } hasErrors |= boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; switch (boundMember.Kind) { case BoundKind.FieldAccess: case BoundKind.PropertyAccess: break; case BoundKind.IndexerAccess: case BoundKind.DynamicIndexerAccess: case BoundKind.EventAccess: default: if (!hasErrors) { switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberName, implicitReceiver.Type, name); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, BindValueKind.RValue, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, memberName, name); break; } hasErrors = true; } break; } if (!hasErrors && !CheckValueKind(node: memberName.Parent, expr: boundMember, valueKind: BindValueKind.RValue, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; } return boundMember.ExpressionSymbol; } private BoundPattern BindTypePattern( TypePatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { var patternType = BindTypeForPattern(node.Type, inputType, diagnostics, ref hasErrors); bool isExplicitNotNullTest = patternType.Type.SpecialType == SpecialType.System_Object; return new BoundTypePattern(node, patternType, isExplicitNotNullTest, inputType, patternType.Type, hasErrors); } private BoundPattern BindRelationalPattern( RelationalPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { BoundExpression value = BindExpressionForPattern(inputType, node.Expression, ref hasErrors, diagnostics, out var constantValueOpt, out _); ExpressionSyntax innerExpression = SkipParensAndNullSuppressions(node.Expression); if (innerExpression.Kind() == SyntaxKind.DefaultLiteralExpression) { diagnostics.Add(ErrorCode.ERR_DefaultPattern, innerExpression.Location); hasErrors = true; } RoslynDebug.Assert(value.Type is { }); BinaryOperatorKind operation = tokenKindToBinaryOperatorKind(node.OperatorToken.Kind()); if (operation == BinaryOperatorKind.Equal) { diagnostics.Add(ErrorCode.ERR_InvalidExprTerm, node.OperatorToken.GetLocation(), node.OperatorToken.Text); hasErrors = true; } BinaryOperatorKind opType = RelationalOperatorType(value.Type.EnumUnderlyingTypeOrSelf()); switch (opType) { case BinaryOperatorKind.Float: case BinaryOperatorKind.Double: if (!hasErrors && constantValueOpt != null && !constantValueOpt.IsBad && double.IsNaN(constantValueOpt.DoubleValue)) { diagnostics.Add(ErrorCode.ERR_RelationalPatternWithNaN, node.Expression.Location); hasErrors = true; } break; case BinaryOperatorKind.String: case BinaryOperatorKind.Bool: case BinaryOperatorKind.Error: if (!hasErrors) { diagnostics.Add(ErrorCode.ERR_UnsupportedTypeForRelationalPattern, node.Location, value.Type.ToDisplayString()); hasErrors = true; } break; } if (constantValueOpt is null) { hasErrors = true; constantValueOpt = ConstantValue.Bad; } return new BoundRelationalPattern(node, operation | opType, value, constantValueOpt, inputType, value.Type, hasErrors); static BinaryOperatorKind tokenKindToBinaryOperatorKind(SyntaxKind kind) => kind switch { SyntaxKind.LessThanEqualsToken => BinaryOperatorKind.LessThanOrEqual, SyntaxKind.LessThanToken => BinaryOperatorKind.LessThan, SyntaxKind.GreaterThanToken => BinaryOperatorKind.GreaterThan, SyntaxKind.GreaterThanEqualsToken => BinaryOperatorKind.GreaterThanOrEqual, // The following occurs in error recovery scenarios _ => BinaryOperatorKind.Equal, }; } /// <summary> /// Compute the type code for the comparison operator to be used. When comparing `byte`s for example, /// the compiler actually uses the operator on the type `int` as there is no corresponding operator for /// the type `byte`. /// </summary> internal static BinaryOperatorKind RelationalOperatorType(TypeSymbol type) => type.SpecialType switch { SpecialType.System_Single => BinaryOperatorKind.Float, SpecialType.System_Double => BinaryOperatorKind.Double, SpecialType.System_Char => BinaryOperatorKind.Char, SpecialType.System_SByte => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Byte => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_UInt16 => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Int16 => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Int32 => BinaryOperatorKind.Int, SpecialType.System_UInt32 => BinaryOperatorKind.UInt, SpecialType.System_Int64 => BinaryOperatorKind.Long, SpecialType.System_UInt64 => BinaryOperatorKind.ULong, SpecialType.System_Decimal => BinaryOperatorKind.Decimal, SpecialType.System_String => BinaryOperatorKind.String, SpecialType.System_Boolean => BinaryOperatorKind.Bool, SpecialType.System_IntPtr when type.IsNativeIntegerType => BinaryOperatorKind.NInt, SpecialType.System_UIntPtr when type.IsNativeIntegerType => BinaryOperatorKind.NUInt, _ => BinaryOperatorKind.Error, }; private BoundPattern BindUnaryPattern( UnaryPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern) { bool permitDesignations = underIsPattern; // prevent designators under 'not' except under an is-pattern var subPattern = BindPattern(node.Pattern, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics, underIsPattern); return new BoundNegatedPattern(node, subPattern, inputType: inputType, narrowedType: inputType, hasErrors); } private BoundPattern BindBinaryPattern( BinaryPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { bool isDisjunction = node.Kind() == SyntaxKind.OrPattern; if (isDisjunction) { permitDesignations = false; // prevent designators under 'or' var left = BindPattern(node.Left, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); var right = BindPattern(node.Right, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); // Compute the common type. This algorithm is quadratic, but disjunctive patterns are unlikely to be huge var narrowedTypeCandidates = ArrayBuilder<TypeSymbol>.GetInstance(2); collectCandidates(left, narrowedTypeCandidates); collectCandidates(right, narrowedTypeCandidates); var narrowedType = leastSpecificType(node, narrowedTypeCandidates, diagnostics) ?? inputType; narrowedTypeCandidates.Free(); return new BoundBinaryPattern(node, disjunction: isDisjunction, left, right, inputType: inputType, narrowedType: narrowedType, hasErrors); static void collectCandidates(BoundPattern pat, ArrayBuilder<TypeSymbol> candidates) { if (pat is BoundBinaryPattern { Disjunction: true } p) { collectCandidates(p.Left, candidates); collectCandidates(p.Right, candidates); } else { candidates.Add(pat.NarrowedType); } } TypeSymbol? leastSpecificType(SyntaxNode node, ArrayBuilder<TypeSymbol> candidates, BindingDiagnosticBag diagnostics) { Debug.Assert(candidates.Count >= 2); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol? bestSoFar = candidates[0]; // first pass: select a candidate for which no other has been shown to be an improvement. for (int i = 1, n = candidates.Count; i < n; i++) { TypeSymbol candidate = candidates[i]; bestSoFar = lessSpecificCandidate(bestSoFar, candidate, ref useSiteInfo) ?? bestSoFar; } // second pass: check that it is no more specific than any candidate. for (int i = 0, n = candidates.Count; i < n; i++) { TypeSymbol candidate = candidates[i]; TypeSymbol? spoiler = lessSpecificCandidate(candidate, bestSoFar, ref useSiteInfo); if (spoiler is null) { bestSoFar = null; break; } // Our specificity criteria are transitive Debug.Assert(spoiler.Equals(bestSoFar, TypeCompareKind.ConsiderEverything)); } diagnostics.Add(node.Location, useSiteInfo); return bestSoFar; } // Given a candidate least specific type so far, attempt to refine it with a possibly less specific candidate. TypeSymbol? lessSpecificCandidate(TypeSymbol bestSoFar, TypeSymbol possiblyLessSpecificCandidate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (bestSoFar.Equals(possiblyLessSpecificCandidate, TypeCompareKind.AllIgnoreOptions)) { // When the types are equivalent, merge them. return bestSoFar.MergeEquivalentTypes(possiblyLessSpecificCandidate, VarianceKind.Out); } else if (Conversions.HasImplicitReferenceConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) { // When there is an implicit reference conversion from T to U, U is less specific return possiblyLessSpecificCandidate; } else if (Conversions.HasBoxingConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) { // when there is a boxing conversion from T to U, U is less specific. return possiblyLessSpecificCandidate; } else { // We have no improved candidate to offer. return null; } } } else { var left = BindPattern(node.Left, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); var leftOutputValEscape = GetValEscape(left.NarrowedType, inputValEscape); var right = BindPattern(node.Right, left.NarrowedType, leftOutputValEscape, permitDesignations, hasErrors, diagnostics); return new BoundBinaryPattern(node, disjunction: isDisjunction, left, right, inputType: inputType, narrowedType: right.NarrowedType, hasErrors); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { partial class Binder { private BoundExpression BindIsPatternExpression(IsPatternExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expression = BindRValueWithoutTargetType(node.Expression, diagnostics); bool hasErrors = IsOperandErrors(node, ref expression, diagnostics); TypeSymbol? expressionType = expression.Type; if (expressionType is null || expressionType.IsVoidType()) { if (!hasErrors) { // value expected diagnostics.Add(ErrorCode.ERR_BadPatternExpression, node.Expression.Location, expression.Display); hasErrors = true; } expression = BadExpression(expression.Syntax, expression); } Debug.Assert(expression.Type is { }); uint inputValEscape = GetValEscape(expression, LocalScopeDepth); BoundPattern pattern = BindPattern(node.Pattern, expression.Type, inputValEscape, permitDesignations: true, hasErrors, diagnostics, underIsPattern: true); hasErrors |= pattern.HasErrors; return MakeIsPatternExpression( node, expression, pattern, GetSpecialType(SpecialType.System_Boolean, diagnostics, node), hasErrors, diagnostics); } private BoundExpression MakeIsPatternExpression( SyntaxNode node, BoundExpression expression, BoundPattern pattern, TypeSymbol boolType, bool hasErrors, BindingDiagnosticBag diagnostics) { // Note that these labels are for the convenience of the compilation of patterns, and are not necessarily emitted into the lowered code. LabelSymbol whenTrueLabel = new GeneratedLabelSymbol("isPatternSuccess"); LabelSymbol whenFalseLabel = new GeneratedLabelSymbol("isPatternFailure"); bool negated = pattern.IsNegated(out var innerPattern); BoundDecisionDag decisionDag = DecisionDagBuilder.CreateDecisionDagForIsPattern( this.Compilation, pattern.Syntax, expression, innerPattern, whenTrueLabel: whenTrueLabel, whenFalseLabel: whenFalseLabel, diagnostics); if (!hasErrors && getConstantResult(decisionDag, negated, whenTrueLabel, whenFalseLabel) is { } constantResult) { if (!constantResult) { Debug.Assert(expression.Type is object); diagnostics.Add(ErrorCode.ERR_IsPatternImpossible, node.Location, expression.Type); hasErrors = true; } else { switch (pattern) { case BoundConstantPattern _: case BoundITuplePattern _: // these patterns can fail in practice throw ExceptionUtilities.Unreachable; case BoundRelationalPattern _: case BoundTypePattern _: case BoundNegatedPattern _: case BoundBinaryPattern _: Debug.Assert(expression.Type is object); diagnostics.Add(ErrorCode.WRN_IsPatternAlways, node.Location, expression.Type); break; case BoundDiscardPattern _: // we do not give a warning on this because it is an existing scenario, and it should // have been obvious in source that it would always match. break; case BoundDeclarationPattern _: case BoundRecursivePattern _: // We do not give a warning on these because people do this to give a name to a value break; } } } else if (expression.ConstantValue != null) { decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(expression); if (!hasErrors && getConstantResult(decisionDag, negated, whenTrueLabel, whenFalseLabel) is { } simplifiedResult) { if (!simplifiedResult) { diagnostics.Add(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, node.Location); } else { switch (pattern) { case BoundConstantPattern _: diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, node.Location); break; case BoundRelationalPattern _: case BoundTypePattern _: case BoundNegatedPattern _: case BoundBinaryPattern _: case BoundDiscardPattern _: diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, node.Location); break; } } } } // decisionDag, whenTrueLabel, and whenFalseLabel represent the decision DAG for the inner pattern, // after removing any outer 'not's, so consumers will need to compensate for negated patterns. return new BoundIsPatternExpression( node, expression, pattern, negated, decisionDag, whenTrueLabel: whenTrueLabel, whenFalseLabel: whenFalseLabel, boolType, hasErrors); static bool? getConstantResult(BoundDecisionDag decisionDag, bool negated, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { if (!decisionDag.ReachableLabels.Contains(whenTrueLabel)) { return negated; } else if (!decisionDag.ReachableLabels.Contains(whenFalseLabel)) { return !negated; } return null; } } private BoundExpression BindSwitchExpression(SwitchExpressionSyntax node, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(node is { }); Binder? switchBinder = this.GetBinder(node); RoslynDebug.Assert(switchBinder is { }); return switchBinder.BindSwitchExpressionCore(node, switchBinder, diagnostics); } internal virtual BoundExpression BindSwitchExpressionCore( SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(this.Next is { }); return this.Next.BindSwitchExpressionCore(node, originalBinder, diagnostics); } internal BoundPattern BindPattern( PatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern = false) { return node switch { DiscardPatternSyntax p => BindDiscardPattern(p, inputType), DeclarationPatternSyntax p => BindDeclarationPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), ConstantPatternSyntax p => BindConstantPatternWithFallbackToTypePattern(p, inputType, hasErrors, diagnostics), RecursivePatternSyntax p => BindRecursivePattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), VarPatternSyntax p => BindVarPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), ParenthesizedPatternSyntax p => BindPattern(p.Pattern, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics, underIsPattern), BinaryPatternSyntax p => BindBinaryPattern(p, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics), UnaryPatternSyntax p => BindUnaryPattern(p, inputType, inputValEscape, hasErrors, diagnostics, underIsPattern), RelationalPatternSyntax p => BindRelationalPattern(p, inputType, hasErrors, diagnostics), TypePatternSyntax p => BindTypePattern(p, inputType, hasErrors, diagnostics), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } private BoundPattern BindDiscardPattern(DiscardPatternSyntax node, TypeSymbol inputType) { return new BoundDiscardPattern(node, inputType: inputType, narrowedType: inputType); } private BoundPattern BindConstantPatternWithFallbackToTypePattern( ConstantPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { return BindConstantPatternWithFallbackToTypePattern(node, node.Expression, inputType, hasErrors, diagnostics); } internal BoundPattern BindConstantPatternWithFallbackToTypePattern( SyntaxNode node, ExpressionSyntax expression, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { ExpressionSyntax innerExpression = SkipParensAndNullSuppressions(expression); if (innerExpression.Kind() == SyntaxKind.DefaultLiteralExpression) { diagnostics.Add(ErrorCode.ERR_DefaultPattern, innerExpression.Location); hasErrors = true; } var convertedExpression = BindExpressionOrTypeForPattern(inputType, innerExpression, ref hasErrors, diagnostics, out var constantValueOpt, out bool wasExpression); if (wasExpression) { return new BoundConstantPattern( node, convertedExpression, constantValueOpt ?? ConstantValue.Bad, inputType, convertedExpression.Type ?? inputType, hasErrors || constantValueOpt is null); } else { if (!hasErrors) CheckFeatureAvailability(innerExpression, MessageID.IDS_FeatureTypePattern, diagnostics); if (hasSuppression(expression)) { diagnostics.Add(ErrorCode.ERR_IllegalSuppression, expression.Location); hasErrors = true; } var boundType = (BoundTypeExpression)convertedExpression; bool isExplicitNotNullTest = boundType.Type.SpecialType == SpecialType.System_Object; return new BoundTypePattern(node, boundType, isExplicitNotNullTest, inputType, boundType.Type, hasErrors); } static bool hasSuppression(ExpressionSyntax e) { while (true) { switch (e) { case ParenthesizedExpressionSyntax p: e = p.Expression; break; case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression }: return true; default: return false; } } } } private ExpressionSyntax SkipParensAndNullSuppressions(ExpressionSyntax e) { while (true) { switch (e) { case ParenthesizedExpressionSyntax p: e = p.Expression; break; case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression } p: e = p.Operand; break; default: return e; } } } /// <summary> /// Binds the expression for a pattern. Sets <paramref name="wasExpression"/> if it was a type rather than an expression, /// and in that case it returns a <see cref="BoundTypeExpression"/>. /// </summary> private BoundExpression BindExpressionOrTypeForPattern( TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression) { constantValueOpt = null; BoundExpression expression = BindTypeOrRValue(patternExpression, diagnostics); wasExpression = expression.Kind != BoundKind.TypeExpression; if (wasExpression) { return BindExpressionForPatternContinued(expression, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt); } else { Debug.Assert(expression is { Kind: BoundKind.TypeExpression, Type: { } }); hasErrors |= CheckValidPatternType(patternExpression, inputType, expression.Type, diagnostics: diagnostics); return expression; } } /// <summary> /// Binds the expression for an is-type right-hand-side, in case it does not bind as a type. /// </summary> private BoundExpression BindExpressionForPattern( TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression) { constantValueOpt = null; var expression = BindExpression(patternExpression, diagnostics: diagnostics, invoked: false, indexed: false); expression = CheckValue(expression, BindValueKind.RValue, diagnostics); wasExpression = expression.Kind switch { BoundKind.BadExpression => false, BoundKind.TypeExpression => false, _ => true }; return wasExpression ? BindExpressionForPatternContinued(expression, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt) : expression; } private BoundExpression BindExpressionForPatternContinued( BoundExpression expression, TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt) { BoundExpression convertedExpression = ConvertPatternExpression( inputType, patternExpression, expression, out constantValueOpt, hasErrors, diagnostics); ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); if (!convertedExpression.HasErrors && !hasErrors) { if (constantValueOpt == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, patternExpression.Location); hasErrors = true; } else if (inputType.IsPointerType()) { CheckFeatureAvailability(patternExpression, MessageID.IDS_FeatureNullPointerConstantPattern, diagnostics, patternExpression.Location); } } if (convertedExpression.Type is null && constantValueOpt != ConstantValue.Null) { Debug.Assert(hasErrors); convertedExpression = new BoundConversion( convertedExpression.Syntax, convertedExpression, Conversion.NoConversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, constantValueOpt: constantValueOpt, conversionGroupOpt: null, type: CreateErrorType(), hasErrors: true) { WasCompilerGenerated = true }; } return convertedExpression; } internal BoundExpression ConvertPatternExpression( TypeSymbol inputType, CSharpSyntaxNode node, BoundExpression expression, out ConstantValue? constantValue, bool hasErrors, BindingDiagnosticBag diagnostics) { BoundExpression convertedExpression; // If we are pattern-matching against an open type, we do not convert the constant to the type of the input. // This permits us to match a value of type `IComparable<T>` with a pattern of type `int`. if (inputType.ContainsTypeParameter()) { convertedExpression = expression; // If the expression does not have a constant value, an error will be reported in the caller if (!hasErrors && expression.ConstantValue is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (expression.ConstantValue == ConstantValue.Null) { // Pointers are value types, but they can be assigned null, so they can be matched against null. if (inputType.IsNonNullableValueType() && !inputType.IsPointerOrFunctionPointer()) { // We do not permit matching null against a struct type. diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, expression.Syntax.Location, inputType); hasErrors = true; } } else { RoslynDebug.Assert(expression.Type is { }); if (ExpressionOfTypeMatchesPatternType(Conversions, inputType, expression.Type, ref useSiteInfo, out _, operandConstantValue: null) == false) { diagnostics.Add(ErrorCode.ERR_PatternWrongType, expression.Syntax.Location, inputType, expression.Display); hasErrors = true; } } if (!hasErrors) { var requiredVersion = MessageID.IDS_FeatureRecursivePatterns.RequiredVersion(); if (Compilation.LanguageVersion < requiredVersion && !this.Conversions.ClassifyConversionFromExpression(expression, inputType, ref useSiteInfo).IsImplicit) { diagnostics.Add(ErrorCode.ERR_ConstantPatternVsOpenType, expression.Syntax.Location, inputType, expression.Display, new CSharpRequiredLanguageVersion(requiredVersion)); } } diagnostics.Add(node, useSiteInfo); } } else { // This will allow user-defined conversions, even though they're not permitted here. This is acceptable // because the result of a user-defined conversion does not have a ConstantValue. A constant pattern // requires a constant value so we'll report a diagnostic to that effect later. convertedExpression = GenerateConversionForAssignment(inputType, expression, diagnostics); if (convertedExpression.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)convertedExpression; BoundExpression operand = conversion.Operand; if (inputType.IsNullableType() && (convertedExpression.ConstantValue == null || !convertedExpression.ConstantValue.IsNull)) { // Null is a special case here because we want to compare null to the Nullable<T> itself, not to the underlying type. // We are not interested in the diagnostic that get created here convertedExpression = CreateConversion(operand, inputType.GetNullableUnderlyingType(), BindingDiagnosticBag.Discarded); } else if ((conversion.ConversionKind == ConversionKind.Boxing || conversion.ConversionKind == ConversionKind.ImplicitReference) && operand.ConstantValue != null && convertedExpression.ConstantValue == null) { // A boxed constant (or string converted to object) is a special case because we prefer // to compare to the pre-converted value by casting the input value to the type of the constant // (that is, unboxing or downcasting it) and then testing the resulting value using primitives. // That is much more efficient than calling object.Equals(x, y), and we can share the downcasted // input value among many constant tests. convertedExpression = operand; } else if (conversion.ConversionKind == ConversionKind.ImplicitNullToPointer || (conversion.ConversionKind == ConversionKind.NoConversion && convertedExpression.Type?.IsErrorType() == true)) { convertedExpression = operand; } } } constantValue = convertedExpression.ConstantValue; return convertedExpression; } /// <summary> /// Check that the pattern type is valid for the operand. Return true if an error was reported. /// </summary> private bool CheckValidPatternType( SyntaxNode typeSyntax, TypeSymbol inputType, TypeSymbol patternType, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert((object)inputType != null); RoslynDebug.Assert((object)patternType != null); if (inputType.IsErrorType() || patternType.IsErrorType()) { return false; } else if (inputType.IsPointerOrFunctionPointer() || patternType.IsPointerOrFunctionPointer()) { // pattern-matching is not permitted for pointer types diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, typeSyntax.Location); return true; } else if (patternType.IsNullableType()) { // It is an error to use pattern-matching with a nullable type, because you'll never get null. Use the underlying type. Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType.GetNullableUnderlyingType()); return true; } else if (typeSyntax is NullableTypeSyntax) { Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType); return true; } else if (patternType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, patternType); return true; } else { if (patternType.IsDynamic()) { Error(diagnostics, ErrorCode.ERR_PatternDynamicType, typeSyntax); return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool? matchPossible = ExpressionOfTypeMatchesPatternType( Conversions, inputType, patternType, ref useSiteInfo, out Conversion conversion, operandConstantValue: null, operandCouldBeNull: true); diagnostics.Add(typeSyntax, useSiteInfo); if (matchPossible != false) { if (!conversion.Exists && (inputType.ContainsTypeParameter() || patternType.ContainsTypeParameter())) { // permit pattern-matching when one of the types is an open type in C# 7.1. LanguageVersion requiredVersion = MessageID.IDS_FeatureGenericPatternMatching.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { Error(diagnostics, ErrorCode.ERR_PatternWrongGenericTypeInVersion, typeSyntax, inputType, patternType, Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); return true; } } } else { Error(diagnostics, ErrorCode.ERR_PatternWrongType, typeSyntax, inputType, patternType); return true; } } return false; } /// <summary> /// Does an expression of type <paramref name="expressionType"/> "match" a pattern that looks for /// type <paramref name="patternType"/>? /// 'true' if the matched type catches all of them, 'false' if it catches none of them, and /// 'null' if it might catch some of them. /// </summary> internal static bool? ExpressionOfTypeMatchesPatternType( Conversions conversions, TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Conversion conversion, ConstantValue? operandConstantValue = null, bool operandCouldBeNull = false) { RoslynDebug.Assert((object)expressionType != null); // Short-circuit a common case. This also improves recovery for some error // cases, e.g. when the type is void. if (expressionType.Equals(patternType, TypeCompareKind.AllIgnoreOptions)) { conversion = Conversion.Identity; return true; } if (expressionType.IsDynamic()) { // if operand is the dynamic type, we do the same thing as though it were object expressionType = conversions.CorLibrary.GetSpecialType(SpecialType.System_Object); } conversion = conversions.ClassifyBuiltInConversion(expressionType, patternType, ref useSiteInfo); ConstantValue result = Binder.GetIsOperatorConstantResult(expressionType, patternType, conversion.Kind, operandConstantValue, operandCouldBeNull); return (result == null) ? (bool?)null : (result == ConstantValue.True) ? true : (result == ConstantValue.False) ? false : throw ExceptionUtilities.UnexpectedValue(result); } private BoundPattern BindDeclarationPattern( DeclarationPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; BoundTypeExpression boundDeclType = BindTypeForPattern(typeSyntax, inputType, diagnostics, ref hasErrors); var valEscape = GetValEscape(boundDeclType.Type, inputValEscape); BindPatternDesignation( designation: node.Designation, declType: boundDeclType.TypeWithAnnotations, valEscape, permitDesignations, typeSyntax, diagnostics, hasErrors: ref hasErrors, variableSymbol: out Symbol? variableSymbol, variableAccess: out BoundExpression? variableAccess); return new BoundDeclarationPattern(node, variableSymbol, variableAccess, boundDeclType, isVar: false, inputType, boundDeclType.Type, hasErrors); } private BoundTypeExpression BindTypeForPattern( TypeSyntax typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors) { RoslynDebug.Assert(inputType is { }); TypeWithAnnotations declType = BindType(typeSyntax, diagnostics, out AliasSymbol aliasOpt); Debug.Assert(declType.HasType); BoundTypeExpression boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, typeWithAnnotations: declType); hasErrors |= CheckValidPatternType(typeSyntax, inputType, declType.Type, diagnostics: diagnostics); return boundDeclType; } private void BindPatternDesignation( VariableDesignationSyntax? designation, TypeWithAnnotations declType, uint inputValEscape, bool permitDesignations, TypeSyntax? typeSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors, out Symbol? variableSymbol, out BoundExpression? variableAccess) { switch (designation) { case SingleVariableDesignationSyntax singleVariableDesignation: SyntaxToken identifier = singleVariableDesignation.Identifier; SourceLocalSymbol localSymbol = this.LookupLocal(identifier); if (!permitDesignations && !identifier.IsMissing) diagnostics.Add(ErrorCode.ERR_DesignatorBeneathPatternCombinator, identifier.GetLocation()); if (localSymbol is { }) { RoslynDebug.Assert(ContainingMemberOrLambda is { }); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) CheckFeatureAvailability(designation, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); localSymbol.SetTypeWithAnnotations(declType); localSymbol.SetValEscape(GetValEscape(declType.Type, inputValEscape)); // Check for variable declaration errors. hasErrors |= localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (!hasErrors) hasErrors = CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax ?? (SyntaxNode)designation); variableSymbol = localSymbol; variableAccess = new BoundLocal( syntax: designation, localSymbol: localSymbol, localSymbol.IsVar ? BoundLocalDeclarationKind.WithInferredType : BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); return; } else { // We should have the right binder in the chain for a script or interactive, so we use the field for the pattern. Debug.Assert(designation.SyntaxTree.Options.Kind != SourceCodeKind.Regular); GlobalExpressionVariable expressionVariableField = LookupDeclaredField(singleVariableDesignation); expressionVariableField.SetTypeWithAnnotations(declType, BindingDiagnosticBag.Discarded); BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); variableSymbol = expressionVariableField; variableAccess = new BoundFieldAccess( syntax: designation, receiver: receiver, fieldSymbol: expressionVariableField, constantValueOpt: null, hasErrors: hasErrors); return; } case DiscardDesignationSyntax _: case null: variableSymbol = null; variableAccess = null; return; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } /// <summary> /// Compute the val escape of an expression of the given <paramref name="type"/>, which is known to be derived /// from an expression whose escape scope is <paramref name="possibleValEscape"/>. By the language rules, the /// result is either that same scope (if the type is a ref struct type) or <see cref="Binder.ExternalScope"/>. /// </summary> private static uint GetValEscape(TypeSymbol type, uint possibleValEscape) { return type.IsRefLikeType ? possibleValEscape : Binder.ExternalScope; } private TypeWithAnnotations BindRecursivePatternType( TypeSyntax? typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors, out BoundTypeExpression? boundDeclType) { if (typeSyntax != null) { boundDeclType = BindTypeForPattern(typeSyntax, inputType, diagnostics, ref hasErrors); return boundDeclType.TypeWithAnnotations; } else { boundDeclType = null; // remove the nullable part of the input's type; e.g. a nullable int becomes an int in a recursive pattern return TypeWithAnnotations.Create(inputType.StrippedType(), NullableAnnotation.NotAnnotated); } } // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this code and its callers. internal static bool IsZeroElementTupleType(TypeSymbol type) { return type.IsStructType() && type.Name == "ValueTuple" && type.GetArity() == 0 && type.ContainingSymbol is var declContainer && declContainer.Kind == SymbolKind.Namespace && declContainer.Name == "System" && (declContainer.ContainingSymbol as NamespaceSymbol)?.IsGlobalNamespace == true; } private BoundPattern BindRecursivePattern( RecursivePatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { if (inputType.IsPointerOrFunctionPointer()) { diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, node.Location); hasErrors = true; inputType = CreateErrorType(); } TypeSyntax? typeSyntax = node.Type; TypeWithAnnotations declTypeWithAnnotations = BindRecursivePatternType(typeSyntax, inputType, diagnostics, ref hasErrors, out BoundTypeExpression? boundDeclType); TypeSymbol declType = declTypeWithAnnotations.Type; inputValEscape = GetValEscape(declType, inputValEscape); MethodSymbol? deconstructMethod = null; ImmutableArray<BoundPositionalSubpattern> deconstructionSubpatterns = default; if (node.PositionalPatternClause != null) { PositionalPatternClauseSyntax positionalClause = node.PositionalPatternClause; var patternsBuilder = ArrayBuilder<BoundPositionalSubpattern>.GetInstance(positionalClause.Subpatterns.Count); if (IsZeroElementTupleType(declType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. BindValueTupleSubpatterns( positionalClause, declType, ImmutableArray<TypeWithAnnotations>.Empty, inputValEscape, permitDesignations, ref hasErrors, patternsBuilder, diagnostics); } else if (declType.IsTupleType) { // It is a tuple type. Work according to its elements BindValueTupleSubpatterns(positionalClause, declType, declType.TupleElementTypesWithAnnotations, inputValEscape, permitDesignations, ref hasErrors, patternsBuilder, diagnostics); } else { // It is not a tuple type. Seek an appropriate Deconstruct method. var inputPlaceholder = new BoundImplicitReceiver(positionalClause, declType); // A fake receiver expression to permit us to reuse binding logic var deconstructDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); BoundExpression deconstruct = MakeDeconstructInvocationExpression( positionalClause.Subpatterns.Count, inputPlaceholder, positionalClause, deconstructDiagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyDeconstructCandidates); if (!anyDeconstructCandidates && ShouldUseITupleForRecursivePattern(node, declType, diagnostics, out var iTupleType, out var iTupleGetLength, out var iTupleGetItem)) { // There was no Deconstruct, but the constraints for the use of ITuple are satisfied. // Use that and forget any errors from trying to bind Deconstruct. deconstructDiagnostics.Free(); BindITupleSubpatterns(positionalClause, patternsBuilder, permitDesignations, diagnostics); deconstructionSubpatterns = patternsBuilder.ToImmutableAndFree(); return new BoundITuplePattern(node, iTupleGetLength, iTupleGetItem, deconstructionSubpatterns, inputType, iTupleType, hasErrors); } else { diagnostics.AddRangeAndFree(deconstructDiagnostics); } deconstructMethod = BindDeconstructSubpatterns( positionalClause, inputValEscape, permitDesignations, deconstruct, outPlaceholders, patternsBuilder, ref hasErrors, diagnostics); } deconstructionSubpatterns = patternsBuilder.ToImmutableAndFree(); } ImmutableArray<BoundPropertySubpattern> properties = default; if (node.PropertyPatternClause != null) { properties = BindPropertyPatternClause(node.PropertyPatternClause, declType, inputValEscape, permitDesignations, diagnostics, ref hasErrors); } BindPatternDesignation( node.Designation, declTypeWithAnnotations, inputValEscape, permitDesignations, typeSyntax, diagnostics, ref hasErrors, out Symbol? variableSymbol, out BoundExpression? variableAccess); bool isExplicitNotNullTest = node.Designation is null && boundDeclType is null && properties.IsDefaultOrEmpty && deconstructMethod is null && deconstructionSubpatterns.IsDefault; return new BoundRecursivePattern( syntax: node, declaredType: boundDeclType, deconstructMethod: deconstructMethod, deconstruction: deconstructionSubpatterns, properties: properties, variable: variableSymbol, variableAccess: variableAccess, isExplicitNotNullTest: isExplicitNotNullTest, inputType: inputType, narrowedType: boundDeclType?.Type ?? inputType.StrippedType(), hasErrors: hasErrors); } private MethodSymbol? BindDeconstructSubpatterns( PositionalPatternClauseSyntax node, uint inputValEscape, bool permitDesignations, BoundExpression deconstruct, ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, ArrayBuilder<BoundPositionalSubpattern> patterns, ref bool hasErrors, BindingDiagnosticBag diagnostics) { var deconstructMethod = deconstruct.ExpressionSymbol as MethodSymbol; if (deconstructMethod is null) hasErrors = true; int skippedExtensionParameters = deconstructMethod?.IsExtensionMethod == true ? 1 : 0; for (int i = 0; i < node.Subpatterns.Count; i++) { var subPattern = node.Subpatterns[i]; bool isError = hasErrors || outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; TypeSymbol elementType = isError ? CreateErrorType() : outPlaceholders[i].Type; ParameterSymbol? parameter = null; if (!isError) { if (subPattern.NameColon != null) { // Check that the given name is the same as the corresponding parameter of the method. int parameterIndex = i + skippedExtensionParameters; if (parameterIndex < deconstructMethod!.ParameterCount) { parameter = deconstructMethod.Parameters[parameterIndex]; string name = subPattern.NameColon.Name.Identifier.ValueText; string parameterName = parameter.Name; if (name != parameterName) { diagnostics.Add(ErrorCode.ERR_DeconstructParameterNameMismatch, subPattern.NameColon.Name.Location, name, parameterName); } } } else if (subPattern.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subPattern.ExpressionColon.Expression.Location); } } var boundSubpattern = new BoundPositionalSubpattern( subPattern, parameter, BindPattern(subPattern.Pattern, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics) ); patterns.Add(boundSubpattern); } return deconstructMethod; } private void BindITupleSubpatterns( PositionalPatternClauseSyntax node, ArrayBuilder<BoundPositionalSubpattern> patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) { // Since the input has been cast to ITuple, it must be escapable. const uint valEscape = Binder.ExternalScope; var objectType = Compilation.GetSpecialType(SpecialType.System_Object); foreach (var subpatternSyntax in node.Subpatterns) { if (subpatternSyntax.NameColon != null) { // error: name not permitted in ITuple deconstruction diagnostics.Add(ErrorCode.ERR_ArgumentNameInITuplePattern, subpatternSyntax.NameColon.Location); } else if (subpatternSyntax.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subpatternSyntax.ExpressionColon.Expression.Location); } var boundSubpattern = new BoundPositionalSubpattern( subpatternSyntax, null, BindPattern(subpatternSyntax.Pattern, objectType, valEscape, permitDesignations, hasErrors: false, diagnostics)); patterns.Add(boundSubpattern); } } private void BindITupleSubpatterns( ParenthesizedVariableDesignationSyntax node, ArrayBuilder<BoundPositionalSubpattern> patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) { // Since the input has been cast to ITuple, it must be escapable. const uint valEscape = Binder.ExternalScope; var objectType = Compilation.GetSpecialType(SpecialType.System_Object); foreach (var variable in node.Variables) { BoundPattern pattern = BindVarDesignation(variable, objectType, valEscape, permitDesignations, hasErrors: false, diagnostics); var boundSubpattern = new BoundPositionalSubpattern( variable, null, pattern); patterns.Add(boundSubpattern); } } private void BindValueTupleSubpatterns( PositionalPatternClauseSyntax node, TypeSymbol declType, ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations, uint inputValEscape, bool permitDesignations, ref bool hasErrors, ArrayBuilder<BoundPositionalSubpattern> patterns, BindingDiagnosticBag diagnostics) { if (elementTypesWithAnnotations.Length != node.Subpatterns.Count && !hasErrors) { diagnostics.Add(ErrorCode.ERR_WrongNumberOfSubpatterns, node.Location, declType, elementTypesWithAnnotations.Length, node.Subpatterns.Count); hasErrors = true; } for (int i = 0; i < node.Subpatterns.Count; i++) { var subpatternSyntax = node.Subpatterns[i]; bool isError = i >= elementTypesWithAnnotations.Length; TypeSymbol elementType = isError ? CreateErrorType() : elementTypesWithAnnotations[i].Type; FieldSymbol? foundField = null; if (!isError) { if (subpatternSyntax.NameColon != null) { string name = subpatternSyntax.NameColon.Name.Identifier.ValueText; foundField = CheckIsTupleElement(subpatternSyntax.NameColon.Name, (NamedTypeSymbol)declType, name, i, diagnostics); } else if (subpatternSyntax.ExpressionColon != null) { diagnostics.Add(ErrorCode.ERR_IdentifierExpected, subpatternSyntax.ExpressionColon.Expression.Location); } } BoundPositionalSubpattern boundSubpattern = new BoundPositionalSubpattern( subpatternSyntax, foundField, BindPattern(subpatternSyntax.Pattern, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics)); patterns.Add(boundSubpattern); } } private bool ShouldUseITupleForRecursivePattern( RecursivePatternSyntax node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) { iTupleType = null; iTupleGetLength = iTupleGetItem = null; if (node.Type != null) { // ITuple matching only applies if no type is given explicitly. return false; } if (node.PropertyPatternClause != null) { // ITuple matching only applies if there is no property pattern part. return false; } if (node.PositionalPatternClause == null) { // ITuple matching only applies if there is a positional pattern part. // This can only occur as a result of syntax error recovery, if at all. return false; } if (node.Designation?.Kind() == SyntaxKind.SingleVariableDesignation) { // ITuple matching only applies if there is no variable declared (what type would the variable be?) return false; } return ShouldUseITuple(node, declType, diagnostics, out iTupleType, out iTupleGetLength, out iTupleGetItem); } private bool ShouldUseITuple( SyntaxNode node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) { iTupleType = null; iTupleGetLength = iTupleGetItem = null; Debug.Assert(!declType.IsTupleType); Debug.Assert(!IsZeroElementTupleType(declType)); if (Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion()) { return false; } iTupleType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_ITuple); if (iTupleType.TypeKind != TypeKind.Interface) { // When compiling to a platform that lacks the interface ITuple (i.e. it is an error type), we simply do not match using it. return false; } // Resolution 2017-11-20 LDM: permit matching via ITuple only for `object`, `ITuple`, and types that are // declared to implement `ITuple`. if (declType != (object)Compilation.GetSpecialType(SpecialType.System_Object) && declType != (object)Compilation.DynamicType && declType != (object)iTupleType && !hasBaseInterface(declType, iTupleType)) { return false; } // Ensure ITuple has a Length and indexer iTupleGetLength = (MethodSymbol?)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length); iTupleGetItem = (MethodSymbol?)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item); if (iTupleGetLength is null || iTupleGetItem is null) { // This might not result in an ideal diagnostic return false; } // passed all the filters; permit using ITuple _ = diagnostics.ReportUseSite(iTupleType, node) || diagnostics.ReportUseSite(iTupleGetLength, node) || diagnostics.ReportUseSite(iTupleGetItem, node); return true; bool hasBaseInterface(TypeSymbol type, NamedTypeSymbol possibleBaseInterface) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Compilation.Conversions.ClassifyBuiltInConversion(type, possibleBaseInterface, ref useSiteInfo).IsImplicit; diagnostics.Add(node, useSiteInfo); return result; } } /// <summary> /// Check that the given name designates a tuple element at the given index, and return that element. /// </summary> private static FieldSymbol? CheckIsTupleElement(SyntaxNode node, NamedTypeSymbol tupleType, string name, int tupleIndex, BindingDiagnosticBag diagnostics) { FieldSymbol? foundElement = null; foreach (var symbol in tupleType.GetMembers(name)) { if (symbol is FieldSymbol field && field.IsTupleElement()) { foundElement = field; break; } } if (foundElement is null || foundElement.TupleElementIndex != tupleIndex) { diagnostics.Add(ErrorCode.ERR_TupleElementNameMismatch, node.Location, name, $"Item{tupleIndex + 1}"); } return foundElement; } private BoundPattern BindVarPattern( VarPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { if ((inputType.IsPointerOrFunctionPointer() && node.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation) || (inputType.IsPointerType() && Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion())) { diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, node.Location); hasErrors = true; inputType = CreateErrorType(); } Symbol foundSymbol = BindTypeOrAliasOrKeyword(node.VarKeyword, node, diagnostics, out bool isVar).Symbol; if (!isVar) { // Give an error if there is a bindable type "var" in scope diagnostics.Add(ErrorCode.ERR_VarMayNotBindToType, node.VarKeyword.GetLocation(), foundSymbol.ToDisplayString()); hasErrors = true; } return BindVarDesignation(node.Designation, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); } private BoundPattern BindVarDesignation( VariableDesignationSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.DiscardDesignation: { return new BoundDiscardPattern(node, inputType: inputType, narrowedType: inputType); } case SyntaxKind.SingleVariableDesignation: { var declType = TypeWithState.ForType(inputType).ToTypeWithAnnotations(Compilation); BindPatternDesignation( designation: node, declType: declType, inputValEscape: inputValEscape, permitDesignations: permitDesignations, typeSyntax: null, diagnostics: diagnostics, hasErrors: ref hasErrors, variableSymbol: out Symbol? variableSymbol, variableAccess: out BoundExpression? variableAccess); var boundOperandType = new BoundTypeExpression(syntax: node, aliasOpt: null, typeWithAnnotations: declType); // fake a type expression for the variable's type // We continue to use a BoundDeclarationPattern for the var pattern, as they have more in common. Debug.Assert(node.Parent is { }); return new BoundDeclarationPattern( node.Parent.Kind() == SyntaxKind.VarPattern ? node.Parent : node, // for `var x` use whole pattern, otherwise use designation for the syntax variableSymbol, variableAccess, boundOperandType, isVar: true, inputType: inputType, narrowedType: inputType, hasErrors: hasErrors); } case SyntaxKind.ParenthesizedVariableDesignation: { var tupleDesignation = (ParenthesizedVariableDesignationSyntax)node; var subPatterns = ArrayBuilder<BoundPositionalSubpattern>.GetInstance(tupleDesignation.Variables.Count); MethodSymbol? deconstructMethod = null; var strippedInputType = inputType.StrippedType(); if (IsZeroElementTupleType(strippedInputType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. addSubpatternsForTuple(ImmutableArray<TypeWithAnnotations>.Empty); } else if (strippedInputType.IsTupleType) { // It is a tuple type. Work according to its elements addSubpatternsForTuple(strippedInputType.TupleElementTypesWithAnnotations); } else { // It is not a tuple type. Seek an appropriate Deconstruct method. var inputPlaceholder = new BoundImplicitReceiver(node, strippedInputType); // A fake receiver expression to permit us to reuse binding logic var deconstructDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); BoundExpression deconstruct = MakeDeconstructInvocationExpression( tupleDesignation.Variables.Count, inputPlaceholder, node, deconstructDiagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyDeconstructCandidates); if (!anyDeconstructCandidates && ShouldUseITuple(node, strippedInputType, diagnostics, out var iTupleType, out var iTupleGetLength, out var iTupleGetItem)) { // There was no applicable candidate Deconstruct, and the constraints for the use of ITuple are satisfied. // Use that and forget any errors from trying to bind Deconstruct. deconstructDiagnostics.Free(); BindITupleSubpatterns(tupleDesignation, subPatterns, permitDesignations, diagnostics); return new BoundITuplePattern(node, iTupleGetLength, iTupleGetItem, subPatterns.ToImmutableAndFree(), strippedInputType, iTupleType, hasErrors); } else { diagnostics.AddRangeAndFree(deconstructDiagnostics); } deconstructMethod = deconstruct.ExpressionSymbol as MethodSymbol; if (!hasErrors) hasErrors = outPlaceholders.IsDefault || tupleDesignation.Variables.Count != outPlaceholders.Length; for (int i = 0; i < tupleDesignation.Variables.Count; i++) { var variable = tupleDesignation.Variables[i]; bool isError = outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; TypeSymbol elementType = isError ? CreateErrorType() : outPlaceholders[i].Type; BoundPattern pattern = BindVarDesignation(variable, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics); subPatterns.Add(new BoundPositionalSubpattern(variable, symbol: null, pattern)); } } return new BoundRecursivePattern( syntax: node, declaredType: null, deconstructMethod: deconstructMethod, deconstruction: subPatterns.ToImmutableAndFree(), properties: default, variable: null, variableAccess: null, isExplicitNotNullTest: false, inputType: inputType, narrowedType: inputType.StrippedType(), hasErrors: hasErrors); void addSubpatternsForTuple(ImmutableArray<TypeWithAnnotations> elementTypes) { if (elementTypes.Length != tupleDesignation.Variables.Count && !hasErrors) { diagnostics.Add(ErrorCode.ERR_WrongNumberOfSubpatterns, tupleDesignation.Location, strippedInputType, elementTypes.Length, tupleDesignation.Variables.Count); hasErrors = true; } for (int i = 0; i < tupleDesignation.Variables.Count; i++) { var variable = tupleDesignation.Variables[i]; bool isError = i >= elementTypes.Length; TypeSymbol elementType = isError ? CreateErrorType() : elementTypes[i].Type; BoundPattern pattern = BindVarDesignation(variable, elementType, GetValEscape(elementType, inputValEscape), permitDesignations, isError, diagnostics); subPatterns.Add(new BoundPositionalSubpattern(variable, symbol: null, pattern)); } } } default: { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } } private ImmutableArray<BoundPropertySubpattern> BindPropertyPatternClause( PropertyPatternClauseSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var builder = ArrayBuilder<BoundPropertySubpattern>.GetInstance(node.Subpatterns.Count); foreach (SubpatternSyntax p in node.Subpatterns) { ExpressionSyntax? expr = p.ExpressionColon?.Expression; PatternSyntax pattern = p.Pattern; BoundPropertySubpatternMember? member; TypeSymbol memberType; if (expr == null) { if (!hasErrors) diagnostics.Add(ErrorCode.ERR_PropertyPatternNameMissing, pattern.Location, pattern); memberType = CreateErrorType(); member = null; hasErrors = true; } else { member = LookupMembersForPropertyPattern(inputType, expr, diagnostics, ref hasErrors); memberType = member.Type; } BoundPattern boundPattern = BindPattern(pattern, memberType, GetValEscape(memberType, inputValEscape), permitDesignations, hasErrors, diagnostics); builder.Add(new BoundPropertySubpattern(p, member, boundPattern)); } return builder.ToImmutableAndFree(); } private BoundPropertySubpatternMember LookupMembersForPropertyPattern( TypeSymbol inputType, ExpressionSyntax expr, BindingDiagnosticBag diagnostics, ref bool hasErrors) { BoundPropertySubpatternMember? receiver = null; Symbol? symbol = null; switch (expr) { case IdentifierNameSyntax name: symbol = BindPropertyPatternMember(inputType, name, ref hasErrors, diagnostics); break; case MemberAccessExpressionSyntax { Name: IdentifierNameSyntax name } memberAccess when memberAccess.IsKind(SyntaxKind.SimpleMemberAccessExpression): receiver = LookupMembersForPropertyPattern(inputType, memberAccess.Expression, diagnostics, ref hasErrors); symbol = BindPropertyPatternMember(receiver.Type.StrippedType(), name, ref hasErrors, diagnostics); break; default: Error(diagnostics, ErrorCode.ERR_InvalidNameInSubpattern, expr); hasErrors = true; break; } TypeSymbol memberType = symbol switch { FieldSymbol field => field.Type, PropertySymbol property => property.Type, _ => CreateErrorType() }; return new BoundPropertySubpatternMember(expr, receiver, symbol, type: memberType, hasErrors); } private Symbol? BindPropertyPatternMember( TypeSymbol inputType, IdentifierNameSyntax memberName, ref bool hasErrors, BindingDiagnosticBag diagnostics) { // TODO: consider refactoring out common code with BindObjectInitializerMember BoundImplicitReceiver implicitReceiver = new BoundImplicitReceiver(memberName, inputType); string name = memberName.Identifier.ValueText; BoundExpression boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: name, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess( (BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); } hasErrors |= boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; switch (boundMember.Kind) { case BoundKind.FieldAccess: case BoundKind.PropertyAccess: break; case BoundKind.IndexerAccess: case BoundKind.DynamicIndexerAccess: case BoundKind.EventAccess: default: if (!hasErrors) { switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberName, implicitReceiver.Type, name); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, BindValueKind.RValue, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, memberName, name); break; } hasErrors = true; } break; } if (!hasErrors && !CheckValueKind(node: memberName.Parent, expr: boundMember, valueKind: BindValueKind.RValue, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; } return boundMember.ExpressionSymbol; } private BoundPattern BindTypePattern( TypePatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { var patternType = BindTypeForPattern(node.Type, inputType, diagnostics, ref hasErrors); bool isExplicitNotNullTest = patternType.Type.SpecialType == SpecialType.System_Object; return new BoundTypePattern(node, patternType, isExplicitNotNullTest, inputType, patternType.Type, hasErrors); } private BoundPattern BindRelationalPattern( RelationalPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) { BoundExpression value = BindExpressionForPattern(inputType, node.Expression, ref hasErrors, diagnostics, out var constantValueOpt, out _); ExpressionSyntax innerExpression = SkipParensAndNullSuppressions(node.Expression); if (innerExpression.Kind() == SyntaxKind.DefaultLiteralExpression) { diagnostics.Add(ErrorCode.ERR_DefaultPattern, innerExpression.Location); hasErrors = true; } RoslynDebug.Assert(value.Type is { }); BinaryOperatorKind operation = tokenKindToBinaryOperatorKind(node.OperatorToken.Kind()); if (operation == BinaryOperatorKind.Equal) { diagnostics.Add(ErrorCode.ERR_InvalidExprTerm, node.OperatorToken.GetLocation(), node.OperatorToken.Text); hasErrors = true; } BinaryOperatorKind opType = RelationalOperatorType(value.Type.EnumUnderlyingTypeOrSelf()); switch (opType) { case BinaryOperatorKind.Float: case BinaryOperatorKind.Double: if (!hasErrors && constantValueOpt != null && !constantValueOpt.IsBad && double.IsNaN(constantValueOpt.DoubleValue)) { diagnostics.Add(ErrorCode.ERR_RelationalPatternWithNaN, node.Expression.Location); hasErrors = true; } break; case BinaryOperatorKind.String: case BinaryOperatorKind.Bool: case BinaryOperatorKind.Error: if (!hasErrors) { diagnostics.Add(ErrorCode.ERR_UnsupportedTypeForRelationalPattern, node.Location, value.Type.ToDisplayString()); hasErrors = true; } break; } if (constantValueOpt is null) { hasErrors = true; constantValueOpt = ConstantValue.Bad; } return new BoundRelationalPattern(node, operation | opType, value, constantValueOpt, inputType, value.Type, hasErrors); static BinaryOperatorKind tokenKindToBinaryOperatorKind(SyntaxKind kind) => kind switch { SyntaxKind.LessThanEqualsToken => BinaryOperatorKind.LessThanOrEqual, SyntaxKind.LessThanToken => BinaryOperatorKind.LessThan, SyntaxKind.GreaterThanToken => BinaryOperatorKind.GreaterThan, SyntaxKind.GreaterThanEqualsToken => BinaryOperatorKind.GreaterThanOrEqual, // The following occurs in error recovery scenarios _ => BinaryOperatorKind.Equal, }; } /// <summary> /// Compute the type code for the comparison operator to be used. When comparing `byte`s for example, /// the compiler actually uses the operator on the type `int` as there is no corresponding operator for /// the type `byte`. /// </summary> internal static BinaryOperatorKind RelationalOperatorType(TypeSymbol type) => type.SpecialType switch { SpecialType.System_Single => BinaryOperatorKind.Float, SpecialType.System_Double => BinaryOperatorKind.Double, SpecialType.System_Char => BinaryOperatorKind.Char, SpecialType.System_SByte => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Byte => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_UInt16 => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Int16 => BinaryOperatorKind.Int, // operands are converted to int SpecialType.System_Int32 => BinaryOperatorKind.Int, SpecialType.System_UInt32 => BinaryOperatorKind.UInt, SpecialType.System_Int64 => BinaryOperatorKind.Long, SpecialType.System_UInt64 => BinaryOperatorKind.ULong, SpecialType.System_Decimal => BinaryOperatorKind.Decimal, SpecialType.System_String => BinaryOperatorKind.String, SpecialType.System_Boolean => BinaryOperatorKind.Bool, SpecialType.System_IntPtr when type.IsNativeIntegerType => BinaryOperatorKind.NInt, SpecialType.System_UIntPtr when type.IsNativeIntegerType => BinaryOperatorKind.NUInt, _ => BinaryOperatorKind.Error, }; private BoundPattern BindUnaryPattern( UnaryPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern) { bool permitDesignations = underIsPattern; // prevent designators under 'not' except under an is-pattern var subPattern = BindPattern(node.Pattern, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics, underIsPattern); return new BoundNegatedPattern(node, subPattern, inputType: inputType, narrowedType: inputType, hasErrors); } private BoundPattern BindBinaryPattern( BinaryPatternSyntax node, TypeSymbol inputType, uint inputValEscape, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) { bool isDisjunction = node.Kind() == SyntaxKind.OrPattern; if (isDisjunction) { permitDesignations = false; // prevent designators under 'or' var left = BindPattern(node.Left, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); var right = BindPattern(node.Right, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); // Compute the common type. This algorithm is quadratic, but disjunctive patterns are unlikely to be huge var narrowedTypeCandidates = ArrayBuilder<TypeSymbol>.GetInstance(2); collectCandidates(left, narrowedTypeCandidates); collectCandidates(right, narrowedTypeCandidates); var narrowedType = leastSpecificType(node, narrowedTypeCandidates, diagnostics) ?? inputType; narrowedTypeCandidates.Free(); return new BoundBinaryPattern(node, disjunction: isDisjunction, left, right, inputType: inputType, narrowedType: narrowedType, hasErrors); static void collectCandidates(BoundPattern pat, ArrayBuilder<TypeSymbol> candidates) { if (pat is BoundBinaryPattern { Disjunction: true } p) { collectCandidates(p.Left, candidates); collectCandidates(p.Right, candidates); } else { candidates.Add(pat.NarrowedType); } } TypeSymbol? leastSpecificType(SyntaxNode node, ArrayBuilder<TypeSymbol> candidates, BindingDiagnosticBag diagnostics) { Debug.Assert(candidates.Count >= 2); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol? bestSoFar = candidates[0]; // first pass: select a candidate for which no other has been shown to be an improvement. for (int i = 1, n = candidates.Count; i < n; i++) { TypeSymbol candidate = candidates[i]; bestSoFar = lessSpecificCandidate(bestSoFar, candidate, ref useSiteInfo) ?? bestSoFar; } // second pass: check that it is no more specific than any candidate. for (int i = 0, n = candidates.Count; i < n; i++) { TypeSymbol candidate = candidates[i]; TypeSymbol? spoiler = lessSpecificCandidate(candidate, bestSoFar, ref useSiteInfo); if (spoiler is null) { bestSoFar = null; break; } // Our specificity criteria are transitive Debug.Assert(spoiler.Equals(bestSoFar, TypeCompareKind.ConsiderEverything)); } diagnostics.Add(node.Location, useSiteInfo); return bestSoFar; } // Given a candidate least specific type so far, attempt to refine it with a possibly less specific candidate. TypeSymbol? lessSpecificCandidate(TypeSymbol bestSoFar, TypeSymbol possiblyLessSpecificCandidate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (bestSoFar.Equals(possiblyLessSpecificCandidate, TypeCompareKind.AllIgnoreOptions)) { // When the types are equivalent, merge them. return bestSoFar.MergeEquivalentTypes(possiblyLessSpecificCandidate, VarianceKind.Out); } else if (Conversions.HasImplicitReferenceConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) { // When there is an implicit reference conversion from T to U, U is less specific return possiblyLessSpecificCandidate; } else if (Conversions.HasBoxingConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) { // when there is a boxing conversion from T to U, U is less specific. return possiblyLessSpecificCandidate; } else { // We have no improved candidate to offer. return null; } } } else { var left = BindPattern(node.Left, inputType, inputValEscape, permitDesignations, hasErrors, diagnostics); var leftOutputValEscape = GetValEscape(left.NarrowedType, inputValEscape); var right = BindPattern(node.Right, left.NarrowedType, leftOutputValEscape, permitDesignations, hasErrors, diagnostics); return new BoundBinaryPattern(node, disjunction: isDisjunction, left, right, inputType: inputType, narrowedType: right.NarrowedType, hasErrors); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around /// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal sealed class RetargetingTypeParameterSymbol : WrappedTypeParameterSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter) : base(underlyingTypeParameter) { Debug.Assert((object)retargetingModule != null); Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol)); _retargetingModule = retargetingModule; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public override Symbol ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol); } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes); } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress)); } internal override bool? IsNotNullable { get { return _underlyingTypeParameter.IsNotNullable; } } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress)); } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around /// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal sealed class RetargetingTypeParameterSymbol : WrappedTypeParameterSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter) : base(underlyingTypeParameter) { Debug.Assert((object)retargetingModule != null); Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol)); _retargetingModule = retargetingModule; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public override Symbol ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol); } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes); } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress)); } internal override bool? IsNotNullable { get { return _underlyingTypeParameter.IsNotNullable; } } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress)); } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Enumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerator : IEnumerator { public static readonly IEnumerator Instance = new Enumerator(); protected Enumerator() { } public object? Current => throw new InvalidOperationException(); public bool MoveNext() { return false; } public void Reset() { throw new InvalidOperationException(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerator : IEnumerator { public static readonly IEnumerator Instance = new Enumerator(); protected Enumerator() { } public object? Current => throw new InvalidOperationException(); public bool MoveNext() { return false; } public void Reset() { throw new InvalidOperationException(); } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Syntax/BreakStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BreakStatementSyntax { public BreakStatementSyntax Update(SyntaxToken breakKeyword, SyntaxToken semicolonToken) => Update(AttributeLists, breakKeyword, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static BreakStatementSyntax BreakStatement(SyntaxToken breakKeyword, SyntaxToken semicolonToken) => BreakStatement(attributeLists: default, breakKeyword, semicolonToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BreakStatementSyntax { public BreakStatementSyntax Update(SyntaxToken breakKeyword, SyntaxToken semicolonToken) => Update(AttributeLists, breakKeyword, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static BreakStatementSyntax BreakStatement(SyntaxToken breakKeyword, SyntaxToken semicolonToken) => BreakStatement(attributeLists: default, breakKeyword, semicolonToken); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Extensions { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public static string GetMemberNavInfoNameOrEmpty(this ISymbol memberSymbol) { return memberSymbol != null ? memberSymbol.ToDisplayString(s_memberDisplayFormat) : string.Empty; } public static string GetNamespaceNavInfoNameOrEmpty(this INamespaceSymbol namespaceSymbol) { if (namespaceSymbol == null) { return string.Empty; } return !namespaceSymbol.IsGlobalNamespace ? namespaceSymbol.ToDisplayString() : string.Empty; } public static string GetTypeNavInfoNameOrEmpty(this ITypeSymbol typeSymbol) { return typeSymbol != null ? typeSymbol.ToDisplayString(s_typeDisplayFormat) : string.Empty; } public static string GetProjectDisplayName(this Project project) { // If the project name is unambiguous within the solution, use that name. Otherwise, use the unique name // provided by IVsSolution3.GetUniqueUINameOfProject. This covers all cases except for a single solution // with two or more multi-targeted projects with the same name and same targets. // // https://github.com/dotnet/roslyn/pull/43800 // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949113 if (IsUnambiguousProjectNameInSolution(project)) { return project.Name; } else if (project.Solution.Workspace is VisualStudioWorkspace workspace && workspace.GetHierarchy(project.Id) is { } hierarchy && (IVsSolution3)ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)) is { } solution) { if (ErrorHandler.Succeeded(solution.GetUniqueUINameOfProject(hierarchy, out var name)) && name != null) { return name; } } return project.Name; // Local functions static bool IsUnambiguousProjectNameInSolution(Project project) { foreach (var other in project.Solution.Projects) { if (other.Id == project.Id) continue; if (other.Name == project.Name) { // Another project with the same name was found in the solution. This project name is _not_ // unambiguous. return false; } } return true; } } public static bool IsVenus(this Project project) { if (!(project.Solution.Workspace is VisualStudioWorkspaceImpl workspace)) { return false; } foreach (var documentId in project.DocumentIds) { if (workspace.TryGetContainedDocument(documentId) != null) { return true; } } return false; } /// <summary> /// Returns a display name for the given project, walking its parent IVsHierarchy chain and /// pre-pending the names of parenting hierarchies (except the solution). /// </summary> public static string GetProjectNavInfoName(this Project project) { var result = project.Name; if (!(project.Solution.Workspace is VisualStudioWorkspace workspace)) { return result; } var hierarchy = workspace.GetHierarchy(project.Id); if (hierarchy == null) { return result; } if (!hierarchy.TryGetName(out result)) { return result; } if (hierarchy.TryGetParentHierarchy(out var parentHierarchy) && !(parentHierarchy is IVsSolution)) { var builder = new StringBuilder(result); while (parentHierarchy != null && !(parentHierarchy is IVsSolution)) { if (parentHierarchy.TryGetName(out var parentName)) { builder.Insert(0, parentName + "\\"); } if (!parentHierarchy.TryGetParentHierarchy(out parentHierarchy)) { break; } } result = builder.ToString(); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Extensions { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public static string GetMemberNavInfoNameOrEmpty(this ISymbol memberSymbol) { return memberSymbol != null ? memberSymbol.ToDisplayString(s_memberDisplayFormat) : string.Empty; } public static string GetNamespaceNavInfoNameOrEmpty(this INamespaceSymbol namespaceSymbol) { if (namespaceSymbol == null) { return string.Empty; } return !namespaceSymbol.IsGlobalNamespace ? namespaceSymbol.ToDisplayString() : string.Empty; } public static string GetTypeNavInfoNameOrEmpty(this ITypeSymbol typeSymbol) { return typeSymbol != null ? typeSymbol.ToDisplayString(s_typeDisplayFormat) : string.Empty; } public static string GetProjectDisplayName(this Project project) { // If the project name is unambiguous within the solution, use that name. Otherwise, use the unique name // provided by IVsSolution3.GetUniqueUINameOfProject. This covers all cases except for a single solution // with two or more multi-targeted projects with the same name and same targets. // // https://github.com/dotnet/roslyn/pull/43800 // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949113 if (IsUnambiguousProjectNameInSolution(project)) { return project.Name; } else if (project.Solution.Workspace is VisualStudioWorkspace workspace && workspace.GetHierarchy(project.Id) is { } hierarchy && (IVsSolution3)ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)) is { } solution) { if (ErrorHandler.Succeeded(solution.GetUniqueUINameOfProject(hierarchy, out var name)) && name != null) { return name; } } return project.Name; // Local functions static bool IsUnambiguousProjectNameInSolution(Project project) { foreach (var other in project.Solution.Projects) { if (other.Id == project.Id) continue; if (other.Name == project.Name) { // Another project with the same name was found in the solution. This project name is _not_ // unambiguous. return false; } } return true; } } public static bool IsVenus(this Project project) { if (!(project.Solution.Workspace is VisualStudioWorkspaceImpl workspace)) { return false; } foreach (var documentId in project.DocumentIds) { if (workspace.TryGetContainedDocument(documentId) != null) { return true; } } return false; } /// <summary> /// Returns a display name for the given project, walking its parent IVsHierarchy chain and /// pre-pending the names of parenting hierarchies (except the solution). /// </summary> public static string GetProjectNavInfoName(this Project project) { var result = project.Name; if (!(project.Solution.Workspace is VisualStudioWorkspace workspace)) { return result; } var hierarchy = workspace.GetHierarchy(project.Id); if (hierarchy == null) { return result; } if (!hierarchy.TryGetName(out result)) { return result; } if (hierarchy.TryGetParentHierarchy(out var parentHierarchy) && !(parentHierarchy is IVsSolution)) { var builder = new StringBuilder(result); while (parentHierarchy != null && !(parentHierarchy is IVsSolution)) { if (parentHierarchy.TryGetName(out var parentName)) { builder.Insert(0, parentName + "\\"); } if (!parentHierarchy.TryGetParentHierarchy(out parentHierarchy)) { break; } } result = builder.ToString(); } return result; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/CodeGen/LocalSlotDebugInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeGen { internal struct LocalSlotDebugInfo : IEquatable<LocalSlotDebugInfo> { public readonly SynthesizedLocalKind SynthesizedKind; public readonly LocalDebugId Id; public LocalSlotDebugInfo(SynthesizedLocalKind synthesizedKind, LocalDebugId id) { this.SynthesizedKind = synthesizedKind; this.Id = id; } public bool Equals(LocalSlotDebugInfo other) { return this.SynthesizedKind == other.SynthesizedKind && this.Id.Equals(other.Id); } public override bool Equals(object? obj) { return obj is LocalSlotDebugInfo && Equals((LocalSlotDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine((int)SynthesizedKind, Id.GetHashCode()); } public override string ToString() { return SynthesizedKind.ToString() + " " + Id.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { internal struct LocalSlotDebugInfo : IEquatable<LocalSlotDebugInfo> { public readonly SynthesizedLocalKind SynthesizedKind; public readonly LocalDebugId Id; public LocalSlotDebugInfo(SynthesizedLocalKind synthesizedKind, LocalDebugId id) { this.SynthesizedKind = synthesizedKind; this.Id = id; } public bool Equals(LocalSlotDebugInfo other) { return this.SynthesizedKind == other.SynthesizedKind && this.Id.Equals(other.Id); } public override bool Equals(object? obj) { return obj is LocalSlotDebugInfo && Equals((LocalSlotDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine((int)SynthesizedKind, Id.GetHashCode()); } public override string ToString() { return SynthesizedKind.ToString() + " " + Id.ToString(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/Operations/Operation.Enumerable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System; using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class Operation : IOperation { /// <summary> /// Implements a struct-based enumerable for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerable)</code>, and will null reference in these cases. /// </summary> [NonDefaultable] internal readonly struct Enumerable : IEnumerable<IOperation> { private readonly Operation _operation; internal Enumerable(Operation operation) { _operation = operation; } public Enumerator GetEnumerator() => new Enumerator(_operation); public ImmutableArray<IOperation> ToImmutableArray() { switch (_operation) { case NoneOperation { Children: var children }: return children; case InvalidOperation { Children: var children }: return children; case var _ when !GetEnumerator().MoveNext(): return ImmutableArray<IOperation>.Empty; default: var builder = ArrayBuilder<IOperation>.GetInstance(); foreach (var child in this) { builder.Add(child); } return builder.ToImmutableAndFree(); } } IEnumerator<IOperation> IEnumerable<IOperation>.GetEnumerator() => this.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } /// <summary> /// Implements a struct-based enumerator for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerator)</code>, and will null reference in these cases. Implementation of the <see cref="Enumerator.MoveNext"/> /// and <see cref="Enumerator.Current"/> members are delegated to the virtual <see cref="Operation.MoveNext(int, int)"/> and /// <see cref="Operation.GetCurrent(int, int)"/> methods, respectively. Calling <see cref="Current"/> after /// <see cref="Enumerator.MoveNext"/> has returned false will throw an <see cref="InvalidOperationException"/>. /// </summary> [NonDefaultable] internal struct Enumerator : IEnumerator<IOperation> { private readonly Operation _operation; private int _currentSlot; private int _currentIndex; public Enumerator(Operation operation) { _operation = operation; _currentSlot = -1; _currentIndex = -1; } public IOperation Current { get { Debug.Assert(_operation != null && _currentSlot >= 0 && _currentIndex >= 0); return _operation.GetCurrent(_currentSlot, _currentIndex); } } public bool MoveNext() { bool result; (result, _currentSlot, _currentIndex) = _operation.MoveNext(_currentSlot, _currentIndex); return result; } void IEnumerator.Reset() { _currentSlot = -1; _currentIndex = -1; } object? IEnumerator.Current => this.Current; void IDisposable.Dispose() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections; using System; using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class Operation : IOperation { /// <summary> /// Implements a struct-based enumerable for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerable)</code>, and will null reference in these cases. /// </summary> [NonDefaultable] internal readonly struct Enumerable : IEnumerable<IOperation> { private readonly Operation _operation; internal Enumerable(Operation operation) { _operation = operation; } public Enumerator GetEnumerator() => new Enumerator(_operation); public ImmutableArray<IOperation> ToImmutableArray() { switch (_operation) { case NoneOperation { Children: var children }: return children; case InvalidOperation { Children: var children }: return children; case var _ when !GetEnumerator().MoveNext(): return ImmutableArray<IOperation>.Empty; default: var builder = ArrayBuilder<IOperation>.GetInstance(); foreach (var child in this) { builder.Add(child); } return builder.ToImmutableAndFree(); } } IEnumerator<IOperation> IEnumerable<IOperation>.GetEnumerator() => this.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } /// <summary> /// Implements a struct-based enumerator for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerator)</code>, and will null reference in these cases. Implementation of the <see cref="Enumerator.MoveNext"/> /// and <see cref="Enumerator.Current"/> members are delegated to the virtual <see cref="Operation.MoveNext(int, int)"/> and /// <see cref="Operation.GetCurrent(int, int)"/> methods, respectively. Calling <see cref="Current"/> after /// <see cref="Enumerator.MoveNext"/> has returned false will throw an <see cref="InvalidOperationException"/>. /// </summary> [NonDefaultable] internal struct Enumerator : IEnumerator<IOperation> { private readonly Operation _operation; private int _currentSlot; private int _currentIndex; public Enumerator(Operation operation) { _operation = operation; _currentSlot = -1; _currentIndex = -1; } public IOperation Current { get { Debug.Assert(_operation != null && _currentSlot >= 0 && _currentIndex >= 0); return _operation.GetCurrent(_currentSlot, _currentIndex); } } public bool MoveNext() { bool result; (result, _currentSlot, _currentIndex) = _operation.MoveNext(_currentSlot, _currentIndex); return result; } void IEnumerator.Reset() { _currentSlot = -1; _currentIndex = -1; } object? IEnumerator.Current => this.Current; void IDisposable.Dispose() { } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Threading; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition { private readonly TEmbeddedMethod _adder; private readonly TEmbeddedMethod _remover; private readonly TEmbeddedMethod _caller; private int _isUsedForComAwareEventBinding; protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) : base(underlyingEvent) { Debug.Assert(adder != null || remover != null); _adder = adder; _remover = remover; _caller = caller; } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TEventSymbol UnderlyingEvent { get { return this.UnderlyingSymbol; } } protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding); internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { if (_isUsedForComAwareEventBinding == 0 && (!isUsedForComAwareEventBinding || Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0)) { Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0); EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); } Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0); } Cci.IMethodReference Cci.IEventDefinition.Adder { get { return _adder; } } Cci.IMethodReference Cci.IEventDefinition.Remover { get { return _remover; } } Cci.IMethodReference Cci.IEventDefinition.Caller { get { return _caller; } } IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context) { if (_adder != null) { yield return _adder; } if (_remover != null) { yield return _remover; } if (_caller != null) { yield return _caller; } } bool Cci.IEventDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IEventDefinition.IsSpecialName { get { return IsSpecialName; } } Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context) { return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } protected TEmbeddedMethod AnAccessor { get { return _adder ?? _remover; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IEventDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Threading; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition { private readonly TEmbeddedMethod _adder; private readonly TEmbeddedMethod _remover; private readonly TEmbeddedMethod _caller; private int _isUsedForComAwareEventBinding; protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) : base(underlyingEvent) { Debug.Assert(adder != null || remover != null); _adder = adder; _remover = remover; _caller = caller; } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TEventSymbol UnderlyingEvent { get { return this.UnderlyingSymbol; } } protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding); internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { if (_isUsedForComAwareEventBinding == 0 && (!isUsedForComAwareEventBinding || Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0)) { Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0); EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); } Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0); } Cci.IMethodReference Cci.IEventDefinition.Adder { get { return _adder; } } Cci.IMethodReference Cci.IEventDefinition.Remover { get { return _remover; } } Cci.IMethodReference Cci.IEventDefinition.Caller { get { return _caller; } } IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context) { if (_adder != null) { yield return _adder; } if (_remover != null) { yield return _remover; } if (_caller != null) { yield return _caller; } } bool Cci.IEventDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IEventDefinition.IsSpecialName { get { return IsSpecialName; } } Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context) { return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } protected TEmbeddedMethod AnAccessor { get { return _adder ?? _remover; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IEventDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedLanguageEditorFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.EmbeddedLanguages; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime { internal class DateAndTimeEmbeddedLanguageEditorFeatures : DateAndTimeEmbeddedLanguageFeatures, IEmbeddedLanguageEditorFeatures { public IBraceMatcher BraceMatcher { get; } public DateAndTimeEmbeddedLanguageEditorFeatures(EmbeddedLanguageInfo info) : base(info) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.EmbeddedLanguages; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime { internal class DateAndTimeEmbeddedLanguageEditorFeatures : DateAndTimeEmbeddedLanguageFeatures, IEmbeddedLanguageEditorFeatures { public IBraceMatcher BraceMatcher { get; } public DateAndTimeEmbeddedLanguageEditorFeatures(EmbeddedLanguageInfo info) : base(info) { } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DelegateKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Delegate" keyword in member declaration contexts ''' </summary> Friend Class DelegateKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Delegate", VBFeaturesResources.Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Delegate) Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Delegate" keyword in member declaration contexts ''' </summary> Friend Class DelegateKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Delegate", VBFeaturesResources.Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Delegate) Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { internal sealed partial class WorkCoordinator { private readonly Registration _registration; private readonly object _gate; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly IDocumentTrackingService _documentTrackingService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly TaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, bool initializeLazily, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _gate = new object(); _listener = listener; _optionService = _registration.Workspace.Services.GetRequiredService<IOptionService>(); _documentTrackingService = _registration.Workspace.Services.GetRequiredService<IDocumentTrackingService>(); // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new TaskQueue(listener, TaskScheduler.Default); var activeFileBackOffTimeSpan = InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpan; var allFilesWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan; var entireProjectWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpan; _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, initializeLazily, _registration, activeFileBackOffTimeSpan, allFilesWorkerBackOffTimeSpan, entireProjectWorkerBackOffTimeSpan, _shutdownToken); var semanticBackOffTimeSpan = InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpan; var projectBackOffTimeSpan = InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpan; _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpan, projectBackOffTimeSpan, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } // subscribe to option changed event after all required fields are set // otherwise, we can get null exception when running OnOptionChanged handler _optionService.OptionChanged += OnOptionChanged; // subscribe to active document changed event for active file background analysis scope. _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; } public int CorrelationId => _registration.CorrelationId; public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile) { // add analyzer _documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile); // and ask to re-analyze whole solution for the given analyzer var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id); Reanalyze(analyzer, scope); } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; _documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); try { shutdownTask.Wait(TimeSpan.FromSeconds(5)); } catch (AggregateException ex) { ex.Handle(e => e is OperationCanceledException); } if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object? sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { Contract.ThrowIfNull(e.Value); var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } if (!_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { // Bail out if solution crawler is disabled. return; } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object? sender, OptionChangedEventArgs e) { // get off from option changed event handler since it runs on UI thread // getting analyzer can be slow for the very first time since it is lazily initialized _eventProcessingQueue.ScheduleTask(nameof(ReanalyzeOnOptionChange), () => { // Force analyze all analyzers if background analysis scope has changed. var forceAnalyze = e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption; // let each analyzer decide what they want on option change foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (forceAnalyze || analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id); Reanalyze(analyzer, scope); } } }, _shutdownToken); } public void Reanalyze(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority = false) { _eventProcessingQueue.ScheduleTask("Reanalyze", () => EnqueueWorkItemAsync(analyzer, scope, highPriority), _shutdownToken); if (scope.HasMultipleDocuments) { // log big reanalysis request from things like fix all, suppress all or option changes // we are not interested in 1 file re-analysis request which can happen from like venus typing var solution = _registration.GetSolutionToAnalyze(); SolutionCrawlerLogger.LogReanalyze( CorrelationId, analyzer, scope.GetDocumentCount(solution), scope.GetLanguagesStringForTelemetry(solution), highPriority); } } private void OnActiveDocumentChanged(object? sender, DocumentId? activeDocumentId) { var solution = _registration.GetSolutionToAnalyze(); if (solution.GetProject(activeDocumentId?.ProjectId) is not { } activeProject) return; RoslynDebug.AssertNotNull(activeDocumentId); var analysisScope = SolutionCrawlerOptions.GetBackgroundAnalysisScope(activeProject); if (analysisScope == BackgroundAnalysisScope.ActiveFile) { // When the active document changes and we are only analyzing the active file, trigger a document // changed event to reanalyze the newly-active file. EnqueueEvent(solution, activeDocumentId, InvocationReasons.DocumentChanged, nameof(OnActiveDocumentChanged)); } } private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvent(args, "OnWorkspaceChanged"); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => e is not OperationCanceledException) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) => oce.CancellationToken == _shutdownToken; private void ProcessEvent(WorkspaceChangeEventArgs args, string eventName) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, eventName); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, eventName); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: ProcessDocumentEvent(args, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(args.Kind); } } private void OnDocumentOpened(object? sender, DocumentEventArgs e) { _eventProcessingQueue.ScheduleTask("OnDocumentOpened", () => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentOpened), _shutdownToken); } private void OnDocumentClosed(object? sender, DocumentEventArgs e) { _eventProcessingQueue.ScheduleTask("OnDocumentClosed", () => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentClosed), _shutdownToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.DocumentRemoved: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, eventName); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: // If an additional file or .editorconfig has changed we need to reanalyze the entire project. Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.ProjectRemoved: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, eventName); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void EnqueueEvent(Solution oldSolution, Solution newSolution, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, string eventName) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken); } private async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons, SyntaxNode? changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(project, documentId, document, currentMember); } } private static Document GetRequiredDocument(Project project, DocumentId documentId, Document? document) => document ?? project.GetRequiredDocument(documentId); private static SyntaxPath? GetSyntaxPath(SyntaxNode? changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) await EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons).ConfigureAwait(false); } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority) { var solution = _registration.GetSolutionToAnalyze(); var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze; foreach (var (project, documentId) in scope.GetDocumentIds(solution)) await EnqueueWorkItemAsync(analyzer, project, documentId, document: null, invocationReasons).ConfigureAwait(false); } private async Task EnqueueWorkItemAsync( IIncrementalAnalyzer analyzer, Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons) { var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync( GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) await EnqueueWorkItemAsync(projectChanges.NewProject, addedDocumentId, document: null, InvocationReasons.DocumentAdded).ConfigureAwait(false); foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetRequiredDocument(changedDocumentId), projectChanges.NewProject.GetRequiredDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) await EnqueueWorkItemAsync(projectChanges.OldProject, removedDocumentId, document: null, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.Name, newProject.Name) || !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions) || !object.Equals(oldProject.DefaultNamespace, newProject.DefaultNamespace) || !object.Equals(oldProject.OutputFilePath, newProject.OutputFilePath) || !object.Equals(oldProject.OutputRefFilePath, newProject.OutputRefFilePath) || !oldProject.CompilationOutputInfo.Equals(newProject.CompilationOutputInfo) || oldProject.State.RunAnalyzers != newProject.State.RunAnalyzers) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService == null) { // For languages that don't use a Roslyn syntax tree, they don't export a document difference service. // The whole document should be considered as changed in that case. await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false); } else { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var project = solution.GetRequiredProject(documentId.ProjectId); return EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetRequiredProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetRequiredProject(projectId); var newProject = newSolution.GetRequiredProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetRequiredProject(documentId.ProjectId); var newProject = newSolution.GetRequiredProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetRequiredDocument(documentId), newProject.GetRequiredDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal TestAccessor GetTestAccessor() { return new TestAccessor(this); } internal readonly struct TestAccessor { private readonly WorkCoordinator _workCoordinator; internal TestAccessor(WorkCoordinator workCoordinator) { _workCoordinator = workCoordinator; } internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _workCoordinator._registration.GetSolutionToAnalyze(); var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, isLowPriority: false, activeMember: null, EmptyAsyncToken.Instance)); } } _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(workers, list); } internal void WaitUntilCompletion() => _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(); } } internal readonly struct ReanalyzeScope { private readonly SolutionId? _solutionId; private readonly ISet<object>? _projectOrDocumentIds; public ReanalyzeScope(SolutionId solutionId) { _solutionId = solutionId; _projectOrDocumentIds = null; } public ReanalyzeScope(IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null) { projectIds ??= SpecializedCollections.EmptyEnumerable<ProjectId>(); documentIds ??= SpecializedCollections.EmptyEnumerable<DocumentId>(); _solutionId = null; _projectOrDocumentIds = new HashSet<object>(projectIds); foreach (var documentId in documentIds) { if (_projectOrDocumentIds.Contains(documentId.ProjectId)) { continue; } _projectOrDocumentIds.Add(documentId); } } public bool HasMultipleDocuments => _solutionId != null || _projectOrDocumentIds?.Count > 1; public string GetLanguagesStringForTelemetry(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { // return empty if given solution is not // same as solution this scope is created for return string.Empty; } using var pool = SharedPools.Default<HashSet<string>>().GetPooledObject(); if (_solutionId != null) { pool.Object.UnionWith(solution.State.ProjectStates.Select(kv => kv.Value.Language)); return string.Join(",", pool.Object); } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: var project = solution.GetProject(projectId); if (project != null) { pool.Object.Add(project.Language); } break; case DocumentId documentId: var document = solution.GetDocument(documentId); if (document != null) { pool.Object.Add(document.Project.Language); } break; default: throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId); } } return string.Join(",", pool.Object); } public int GetDocumentCount(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { return 0; } var count = 0; if (_solutionId != null) { foreach (var projectState in solution.State.ProjectStates) { count += projectState.Value.DocumentStates.Count; } return count; } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: var project = solution.GetProject(projectId); if (project != null) { count += project.DocumentIds.Count; } break; case DocumentId documentId: count++; break; default: throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId); } } return count; } public IEnumerable<(Project project, DocumentId documentId)> GetDocumentIds(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { yield break; } if (_solutionId != null) { foreach (var project in solution.Projects) { foreach (var documentId in project.DocumentIds) yield return (project, documentId); } yield break; } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: { var project = solution.GetProject(projectId); if (project != null) { foreach (var documentId in project.DocumentIds) yield return (project, documentId); } break; } case DocumentId documentId: { var project = solution.GetProject(documentId.ProjectId); if (project != null) yield return (project, documentId); break; } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { internal sealed partial class WorkCoordinator { private readonly Registration _registration; private readonly object _gate; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly IDocumentTrackingService _documentTrackingService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly TaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, bool initializeLazily, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _gate = new object(); _listener = listener; _optionService = _registration.Workspace.Services.GetRequiredService<IOptionService>(); _documentTrackingService = _registration.Workspace.Services.GetRequiredService<IDocumentTrackingService>(); // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new TaskQueue(listener, TaskScheduler.Default); var activeFileBackOffTimeSpan = InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpan; var allFilesWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan; var entireProjectWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpan; _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, initializeLazily, _registration, activeFileBackOffTimeSpan, allFilesWorkerBackOffTimeSpan, entireProjectWorkerBackOffTimeSpan, _shutdownToken); var semanticBackOffTimeSpan = InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpan; var projectBackOffTimeSpan = InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpan; _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpan, projectBackOffTimeSpan, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } // subscribe to option changed event after all required fields are set // otherwise, we can get null exception when running OnOptionChanged handler _optionService.OptionChanged += OnOptionChanged; // subscribe to active document changed event for active file background analysis scope. _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; } public int CorrelationId => _registration.CorrelationId; public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile) { // add analyzer _documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile); // and ask to re-analyze whole solution for the given analyzer var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id); Reanalyze(analyzer, scope); } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; _documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); try { shutdownTask.Wait(TimeSpan.FromSeconds(5)); } catch (AggregateException ex) { ex.Handle(e => e is OperationCanceledException); } if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object? sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { Contract.ThrowIfNull(e.Value); var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } if (!_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { // Bail out if solution crawler is disabled. return; } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object? sender, OptionChangedEventArgs e) { // get off from option changed event handler since it runs on UI thread // getting analyzer can be slow for the very first time since it is lazily initialized _eventProcessingQueue.ScheduleTask(nameof(ReanalyzeOnOptionChange), () => { // Force analyze all analyzers if background analysis scope has changed. var forceAnalyze = e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption; // let each analyzer decide what they want on option change foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (forceAnalyze || analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id); Reanalyze(analyzer, scope); } } }, _shutdownToken); } public void Reanalyze(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority = false) { _eventProcessingQueue.ScheduleTask("Reanalyze", () => EnqueueWorkItemAsync(analyzer, scope, highPriority), _shutdownToken); if (scope.HasMultipleDocuments) { // log big reanalysis request from things like fix all, suppress all or option changes // we are not interested in 1 file re-analysis request which can happen from like venus typing var solution = _registration.GetSolutionToAnalyze(); SolutionCrawlerLogger.LogReanalyze( CorrelationId, analyzer, scope.GetDocumentCount(solution), scope.GetLanguagesStringForTelemetry(solution), highPriority); } } private void OnActiveDocumentChanged(object? sender, DocumentId? activeDocumentId) { var solution = _registration.GetSolutionToAnalyze(); if (solution.GetProject(activeDocumentId?.ProjectId) is not { } activeProject) return; RoslynDebug.AssertNotNull(activeDocumentId); var analysisScope = SolutionCrawlerOptions.GetBackgroundAnalysisScope(activeProject); if (analysisScope == BackgroundAnalysisScope.ActiveFile) { // When the active document changes and we are only analyzing the active file, trigger a document // changed event to reanalyze the newly-active file. EnqueueEvent(solution, activeDocumentId, InvocationReasons.DocumentChanged, nameof(OnActiveDocumentChanged)); } } private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvent(args, "OnWorkspaceChanged"); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => e is not OperationCanceledException) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) => oce.CancellationToken == _shutdownToken; private void ProcessEvent(WorkspaceChangeEventArgs args, string eventName) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, eventName); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, eventName); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: ProcessDocumentEvent(args, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(args.Kind); } } private void OnDocumentOpened(object? sender, DocumentEventArgs e) { _eventProcessingQueue.ScheduleTask("OnDocumentOpened", () => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentOpened), _shutdownToken); } private void OnDocumentClosed(object? sender, DocumentEventArgs e) { _eventProcessingQueue.ScheduleTask("OnDocumentClosed", () => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentClosed), _shutdownToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.DocumentRemoved: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: Contract.ThrowIfNull(e.DocumentId); EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, eventName); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: // If an additional file or .editorconfig has changed we need to reanalyze the entire project. Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.ProjectRemoved: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: Contract.ThrowIfNull(e.ProjectId); EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, string eventName) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, eventName); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, eventName); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, eventName); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, eventName); break; default: throw ExceptionUtilities.UnexpectedValue(e.Kind); } } private void EnqueueEvent(Solution oldSolution, Solution newSolution, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, string eventName) { _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, string eventName) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask(eventName, () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken); } private async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons, SyntaxNode? changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(project, documentId, document, currentMember); } } private static Document GetRequiredDocument(Project project, DocumentId documentId, Document? document) => document ?? project.GetRequiredDocument(documentId); private static SyntaxPath? GetSyntaxPath(SyntaxNode? changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) await EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons).ConfigureAwait(false); } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority) { var solution = _registration.GetSolutionToAnalyze(); var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze; foreach (var (project, documentId) in scope.GetDocumentIds(solution)) await EnqueueWorkItemAsync(analyzer, project, documentId, document: null, invocationReasons).ConfigureAwait(false); } private async Task EnqueueWorkItemAsync( IIncrementalAnalyzer analyzer, Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons) { var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync( GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) await EnqueueWorkItemAsync(projectChanges.NewProject, addedDocumentId, document: null, InvocationReasons.DocumentAdded).ConfigureAwait(false); foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetRequiredDocument(changedDocumentId), projectChanges.NewProject.GetRequiredDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) await EnqueueWorkItemAsync(projectChanges.OldProject, removedDocumentId, document: null, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.Name, newProject.Name) || !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions) || !object.Equals(oldProject.DefaultNamespace, newProject.DefaultNamespace) || !object.Equals(oldProject.OutputFilePath, newProject.OutputFilePath) || !object.Equals(oldProject.OutputRefFilePath, newProject.OutputRefFilePath) || !oldProject.CompilationOutputInfo.Equals(newProject.CompilationOutputInfo) || oldProject.State.RunAnalyzers != newProject.State.RunAnalyzers) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService == null) { // For languages that don't use a Roslyn syntax tree, they don't export a document difference service. // The whole document should be considered as changed in that case. await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false); } else { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var project = solution.GetRequiredProject(documentId.ProjectId); return EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetRequiredProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetRequiredProject(projectId); var newProject = newSolution.GetRequiredProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetRequiredProject(documentId.ProjectId); var newProject = newSolution.GetRequiredProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetRequiredDocument(documentId), newProject.GetRequiredDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal TestAccessor GetTestAccessor() { return new TestAccessor(this); } internal readonly struct TestAccessor { private readonly WorkCoordinator _workCoordinator; internal TestAccessor(WorkCoordinator workCoordinator) { _workCoordinator = workCoordinator; } internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _workCoordinator._registration.GetSolutionToAnalyze(); var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, isLowPriority: false, activeMember: null, EmptyAsyncToken.Instance)); } } _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(workers, list); } internal void WaitUntilCompletion() => _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(); } } internal readonly struct ReanalyzeScope { private readonly SolutionId? _solutionId; private readonly ISet<object>? _projectOrDocumentIds; public ReanalyzeScope(SolutionId solutionId) { _solutionId = solutionId; _projectOrDocumentIds = null; } public ReanalyzeScope(IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null) { projectIds ??= SpecializedCollections.EmptyEnumerable<ProjectId>(); documentIds ??= SpecializedCollections.EmptyEnumerable<DocumentId>(); _solutionId = null; _projectOrDocumentIds = new HashSet<object>(projectIds); foreach (var documentId in documentIds) { if (_projectOrDocumentIds.Contains(documentId.ProjectId)) { continue; } _projectOrDocumentIds.Add(documentId); } } public bool HasMultipleDocuments => _solutionId != null || _projectOrDocumentIds?.Count > 1; public string GetLanguagesStringForTelemetry(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { // return empty if given solution is not // same as solution this scope is created for return string.Empty; } using var pool = SharedPools.Default<HashSet<string>>().GetPooledObject(); if (_solutionId != null) { pool.Object.UnionWith(solution.State.ProjectStates.Select(kv => kv.Value.Language)); return string.Join(",", pool.Object); } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: var project = solution.GetProject(projectId); if (project != null) { pool.Object.Add(project.Language); } break; case DocumentId documentId: var document = solution.GetDocument(documentId); if (document != null) { pool.Object.Add(document.Project.Language); } break; default: throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId); } } return string.Join(",", pool.Object); } public int GetDocumentCount(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { return 0; } var count = 0; if (_solutionId != null) { foreach (var projectState in solution.State.ProjectStates) { count += projectState.Value.DocumentStates.Count; } return count; } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: var project = solution.GetProject(projectId); if (project != null) { count += project.DocumentIds.Count; } break; case DocumentId documentId: count++; break; default: throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId); } } return count; } public IEnumerable<(Project project, DocumentId documentId)> GetDocumentIds(Solution solution) { if (_solutionId != null && solution.Id != _solutionId) { yield break; } if (_solutionId != null) { foreach (var project in solution.Projects) { foreach (var documentId in project.DocumentIds) yield return (project, documentId); } yield break; } Contract.ThrowIfNull(_projectOrDocumentIds); foreach (var projectOrDocumentId in _projectOrDocumentIds) { switch (projectOrDocumentId) { case ProjectId projectId: { var project = solution.GetProject(projectId); if (project != null) { foreach (var documentId in project.DocumentIds) yield return (project, documentId); } break; } case DocumentId documentId: { var project = solution.GetProject(documentId.ProjectId); if (project != null) yield return (project, documentId); break; } } } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.Rewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicExtensionMethodReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode CancellationToken.ThrowIfCancellationRequested() Return SimplifyExpression( node, newNode:=MyBase.VisitInvocationExpression(node), simplifier:=s_simplifyInvocationExpression) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicExtensionMethodReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode CancellationToken.ThrowIfCancellationRequested() Return SimplifyExpression( node, newNode:=MyBase.VisitInvocationExpression(node), simplifier:=s_simplifyInvocationExpression) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Tools/Source/RunTests/Options.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Mono.Options; namespace RunTests { internal enum Display { None, All, Succeeded, Failed, } internal class Options { /// <summary> /// Use HTML output files. /// </summary> public bool IncludeHtml { get; set; } /// <summary> /// Display the results files. /// </summary> public Display Display { get; set; } /// <summary> /// Filter string to pass to xunit. /// </summary> public string? TestFilter { get; set; } public string Configuration { get; set; } /// <summary> /// The set of target frameworks that should be probed for test assemblies. /// </summary> public List<string> TargetFrameworks { get; set; } = new List<string>(); public List<string> IncludeFilter { get; set; } = new List<string>(); public List<string> ExcludeFilter { get; set; } = new List<string>(); public string ArtifactsDirectory { get; } /// <summary> /// Time after which the runner should kill the xunit process and exit with a failure. /// </summary> public TimeSpan? Timeout { get; set; } /// <summary> /// Retry tests on failure /// </summary> public bool Retry { get; set; } /// <summary> /// Whether or not to collect dumps on crashes and timeouts. /// </summary> public bool CollectDumps { get; set; } /// <summary> /// The path to procdump.exe /// </summary> public string? ProcDumpFilePath { get; set; } /// <summary> /// Disable partitioning and parallelization across test assemblies. /// </summary> public bool Sequential { get; set; } /// <summary> /// Whether to run test partitions as Helix work items. /// </summary> public bool UseHelix { get; set; } /// <summary> /// Name of the Helix queue to run tests on (only valid when <see cref="UseHelix" /> is <see langword="true" />). /// </summary> public string? HelixQueueName { get; set; } /// <summary> /// Path to the dotnet executable we should use for running dotnet test /// </summary> public string DotnetFilePath { get; set; } /// <summary> /// Directory to hold all of the xml files created as test results. /// </summary> public string TestResultsDirectory { get; set; } /// <summary> /// Directory to hold dump files and other log files created while running tests. /// </summary> public string LogFilesDirectory { get; set; } public string Platform { get; set; } public Options( string dotnetFilePath, string artifactsDirectory, string configuration, string testResultsDirectory, string logFilesDirectory, string platform) { DotnetFilePath = dotnetFilePath; ArtifactsDirectory = artifactsDirectory; Configuration = configuration; TestResultsDirectory = testResultsDirectory; LogFilesDirectory = logFilesDirectory; Platform = platform; } internal static Options? Parse(string[] args) { string? dotnetFilePath = null; var platform = "x64"; var includeHtml = false; var targetFrameworks = new List<string>(); var configuration = "Debug"; var includeFilter = new List<string>(); var excludeFilter = new List<string>(); var sequential = false; var helix = false; var helixQueueName = "Windows.10.Amd64.Open"; var retry = false; string? testFilter = null; int? timeout = null; string? resultFileDirectory = null; string? logFileDirectory = null; var display = Display.None; var collectDumps = false; string? procDumpFilePath = null; string? artifactsPath = null; var optionSet = new OptionSet() { { "dotnet=", "Path to dotnet", (string s) => dotnetFilePath = s }, { "configuration=", "Configuration to test: Debug or Release", (string s) => configuration = s }, { "tfm=", "Target framework to test", (string s) => targetFrameworks.Add(s) }, { "include=", "Expression for including unit test dlls: default *.UnitTests.dll", (string s) => includeFilter.Add(s) }, { "exclude=", "Expression for excluding unit test dlls: default is empty", (string s) => excludeFilter.Add(s) }, { "platform=", "Platform to test: x86 or x64", (string s) => platform = s }, { "html", "Include HTML file output", o => includeHtml = o is object }, { "sequential", "Run tests sequentially", o => sequential = o is object }, { "helix", "Run tests on Helix", o => helix = o is object }, { "helixQueueName=", "Name of the Helix queue to run tests on", (string s) => helixQueueName = s }, { "testfilter=", "xUnit string to pass to --filter, e.g. FullyQualifiedName~TestClass1|Category=CategoryA", (string s) => testFilter = s }, { "timeout=", "Minute timeout to limit the tests to", (int i) => timeout = i }, { "out=", "Test result file directory (when running on Helix, this is relative to the Helix work item directory)", (string s) => resultFileDirectory = s }, { "logs=", "Log file directory (when running on Helix, this is relative to the Helix work item directory)", (string s) => logFileDirectory = s }, { "display=", "Display", (Display d) => display = d }, { "artifactspath=", "Path to the artifacts directory", (string s) => artifactsPath = s }, { "procdumppath=", "Path to procdump", (string s) => procDumpFilePath = s }, { "collectdumps", "Whether or not to gather dumps on timeouts and crashes", o => collectDumps = o is object }, { "retry", "Retry failed test a few times", o => retry = o is object }, }; List<string> assemblyList; try { assemblyList = optionSet.Parse(args); } catch (OptionException e) { ConsoleUtil.WriteLine($"Error parsing command line arguments: {e.Message}"); optionSet.WriteOptionDescriptions(Console.Out); return null; } if (includeFilter.Count == 0) { includeFilter.Add(".*UnitTests.*"); } if (targetFrameworks.Count == 0) { targetFrameworks.Add("net472"); } artifactsPath ??= TryGetArtifactsPath(); if (artifactsPath is null || !Directory.Exists(artifactsPath)) { ConsoleUtil.WriteLine($"Did not find artifacts directory at {artifactsPath}"); return null; } resultFileDirectory ??= helix ? "." : Path.Combine(artifactsPath, "TestResults", configuration); logFileDirectory ??= resultFileDirectory; dotnetFilePath ??= TryGetDotNetPath(); if (dotnetFilePath is null || !File.Exists(dotnetFilePath)) { ConsoleUtil.WriteLine($"Did not find 'dotnet' at {dotnetFilePath}"); return null; } if (retry && includeHtml) { ConsoleUtil.WriteLine($"Cannot specify both --retry and --html"); return null; } if (procDumpFilePath is { } && !collectDumps) { ConsoleUtil.WriteLine($"procdumppath was specified without collectdumps hence it will not be used"); } return new Options( dotnetFilePath: dotnetFilePath, artifactsDirectory: artifactsPath, configuration: configuration, testResultsDirectory: resultFileDirectory, logFilesDirectory: logFileDirectory, platform: platform) { TargetFrameworks = targetFrameworks, IncludeFilter = includeFilter, ExcludeFilter = excludeFilter, Display = display, ProcDumpFilePath = procDumpFilePath, CollectDumps = collectDumps, Sequential = sequential, UseHelix = helix, HelixQueueName = helixQueueName, IncludeHtml = includeHtml, TestFilter = testFilter, Timeout = timeout is { } t ? TimeSpan.FromMinutes(t) : null, Retry = retry, }; static string? TryGetArtifactsPath() { var path = AppContext.BaseDirectory; while (path is object && Path.GetFileName(path) != "artifacts") { path = Path.GetDirectoryName(path); } return path; } static string? TryGetDotNetPath() { var dir = RuntimeEnvironment.GetRuntimeDirectory(); var programName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; while (dir != null && !File.Exists(Path.Combine(dir, programName))) { dir = Path.GetDirectoryName(dir); } return dir == null ? null : Path.Combine(dir, programName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Mono.Options; namespace RunTests { internal enum Display { None, All, Succeeded, Failed, } internal class Options { /// <summary> /// Use HTML output files. /// </summary> public bool IncludeHtml { get; set; } /// <summary> /// Display the results files. /// </summary> public Display Display { get; set; } /// <summary> /// Filter string to pass to xunit. /// </summary> public string? TestFilter { get; set; } public string Configuration { get; set; } /// <summary> /// The set of target frameworks that should be probed for test assemblies. /// </summary> public List<string> TargetFrameworks { get; set; } = new List<string>(); public List<string> IncludeFilter { get; set; } = new List<string>(); public List<string> ExcludeFilter { get; set; } = new List<string>(); public string ArtifactsDirectory { get; } /// <summary> /// Time after which the runner should kill the xunit process and exit with a failure. /// </summary> public TimeSpan? Timeout { get; set; } /// <summary> /// Retry tests on failure /// </summary> public bool Retry { get; set; } /// <summary> /// Whether or not to collect dumps on crashes and timeouts. /// </summary> public bool CollectDumps { get; set; } /// <summary> /// The path to procdump.exe /// </summary> public string? ProcDumpFilePath { get; set; } /// <summary> /// Disable partitioning and parallelization across test assemblies. /// </summary> public bool Sequential { get; set; } /// <summary> /// Whether to run test partitions as Helix work items. /// </summary> public bool UseHelix { get; set; } /// <summary> /// Name of the Helix queue to run tests on (only valid when <see cref="UseHelix" /> is <see langword="true" />). /// </summary> public string? HelixQueueName { get; set; } /// <summary> /// Path to the dotnet executable we should use for running dotnet test /// </summary> public string DotnetFilePath { get; set; } /// <summary> /// Directory to hold all of the xml files created as test results. /// </summary> public string TestResultsDirectory { get; set; } /// <summary> /// Directory to hold dump files and other log files created while running tests. /// </summary> public string LogFilesDirectory { get; set; } public string Platform { get; set; } public Options( string dotnetFilePath, string artifactsDirectory, string configuration, string testResultsDirectory, string logFilesDirectory, string platform) { DotnetFilePath = dotnetFilePath; ArtifactsDirectory = artifactsDirectory; Configuration = configuration; TestResultsDirectory = testResultsDirectory; LogFilesDirectory = logFilesDirectory; Platform = platform; } internal static Options? Parse(string[] args) { string? dotnetFilePath = null; var platform = "x64"; var includeHtml = false; var targetFrameworks = new List<string>(); var configuration = "Debug"; var includeFilter = new List<string>(); var excludeFilter = new List<string>(); var sequential = false; var helix = false; var helixQueueName = "Windows.10.Amd64.Open"; var retry = false; string? testFilter = null; int? timeout = null; string? resultFileDirectory = null; string? logFileDirectory = null; var display = Display.None; var collectDumps = false; string? procDumpFilePath = null; string? artifactsPath = null; var optionSet = new OptionSet() { { "dotnet=", "Path to dotnet", (string s) => dotnetFilePath = s }, { "configuration=", "Configuration to test: Debug or Release", (string s) => configuration = s }, { "tfm=", "Target framework to test", (string s) => targetFrameworks.Add(s) }, { "include=", "Expression for including unit test dlls: default *.UnitTests.dll", (string s) => includeFilter.Add(s) }, { "exclude=", "Expression for excluding unit test dlls: default is empty", (string s) => excludeFilter.Add(s) }, { "platform=", "Platform to test: x86 or x64", (string s) => platform = s }, { "html", "Include HTML file output", o => includeHtml = o is object }, { "sequential", "Run tests sequentially", o => sequential = o is object }, { "helix", "Run tests on Helix", o => helix = o is object }, { "helixQueueName=", "Name of the Helix queue to run tests on", (string s) => helixQueueName = s }, { "testfilter=", "xUnit string to pass to --filter, e.g. FullyQualifiedName~TestClass1|Category=CategoryA", (string s) => testFilter = s }, { "timeout=", "Minute timeout to limit the tests to", (int i) => timeout = i }, { "out=", "Test result file directory (when running on Helix, this is relative to the Helix work item directory)", (string s) => resultFileDirectory = s }, { "logs=", "Log file directory (when running on Helix, this is relative to the Helix work item directory)", (string s) => logFileDirectory = s }, { "display=", "Display", (Display d) => display = d }, { "artifactspath=", "Path to the artifacts directory", (string s) => artifactsPath = s }, { "procdumppath=", "Path to procdump", (string s) => procDumpFilePath = s }, { "collectdumps", "Whether or not to gather dumps on timeouts and crashes", o => collectDumps = o is object }, { "retry", "Retry failed test a few times", o => retry = o is object }, }; List<string> assemblyList; try { assemblyList = optionSet.Parse(args); } catch (OptionException e) { ConsoleUtil.WriteLine($"Error parsing command line arguments: {e.Message}"); optionSet.WriteOptionDescriptions(Console.Out); return null; } if (includeFilter.Count == 0) { includeFilter.Add(".*UnitTests.*"); } if (targetFrameworks.Count == 0) { targetFrameworks.Add("net472"); } artifactsPath ??= TryGetArtifactsPath(); if (artifactsPath is null || !Directory.Exists(artifactsPath)) { ConsoleUtil.WriteLine($"Did not find artifacts directory at {artifactsPath}"); return null; } resultFileDirectory ??= helix ? "." : Path.Combine(artifactsPath, "TestResults", configuration); logFileDirectory ??= resultFileDirectory; dotnetFilePath ??= TryGetDotNetPath(); if (dotnetFilePath is null || !File.Exists(dotnetFilePath)) { ConsoleUtil.WriteLine($"Did not find 'dotnet' at {dotnetFilePath}"); return null; } if (retry && includeHtml) { ConsoleUtil.WriteLine($"Cannot specify both --retry and --html"); return null; } if (procDumpFilePath is { } && !collectDumps) { ConsoleUtil.WriteLine($"procdumppath was specified without collectdumps hence it will not be used"); } return new Options( dotnetFilePath: dotnetFilePath, artifactsDirectory: artifactsPath, configuration: configuration, testResultsDirectory: resultFileDirectory, logFilesDirectory: logFileDirectory, platform: platform) { TargetFrameworks = targetFrameworks, IncludeFilter = includeFilter, ExcludeFilter = excludeFilter, Display = display, ProcDumpFilePath = procDumpFilePath, CollectDumps = collectDumps, Sequential = sequential, UseHelix = helix, HelixQueueName = helixQueueName, IncludeHtml = includeHtml, TestFilter = testFilter, Timeout = timeout is { } t ? TimeSpan.FromMinutes(t) : null, Retry = retry, }; static string? TryGetArtifactsPath() { var path = AppContext.BaseDirectory; while (path is object && Path.GetFileName(path) != "artifacts") { path = Path.GetDirectoryName(path); } return path; } static string? TryGetDotNetPath() { var dir = RuntimeEnvironment.GetRuntimeDirectory(); var programName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; while (dir != null && !File.Exists(Path.Combine(dir, programName))) { dir = Path.GetDirectoryName(dir); } return dir == null ? null : Path.Combine(dir, programName); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { /// <summary> /// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer { private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof; public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp) { } protected override bool IsValidTypeofAction(OperationAnalysisContext context) { var node = context.Operation.Syntax; var syntaxTree = node.SyntaxTree; // nameof was added in CSharp 6.0, so don't offer it for any languages before that time if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6) { return false; } // Make sure that the syntax that we're looking at is actually a typeof expression and that // the parent syntax is a member access expression otherwise the syntax is not the kind of // expression that we want to analyze return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression && // nameof(System.Void) isn't allowed in C#. typeofExpression is not { Type: PredefinedTypeSyntax { Keyword: { RawKind: (int)SyntaxKind.VoidKeyword } } }; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { /// <summary> /// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer { private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof; public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp) { } protected override bool IsValidTypeofAction(OperationAnalysisContext context) { var node = context.Operation.Syntax; var syntaxTree = node.SyntaxTree; // nameof was added in CSharp 6.0, so don't offer it for any languages before that time if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6) { return false; } // Make sure that the syntax that we're looking at is actually a typeof expression and that // the parent syntax is a member access expression otherwise the syntax is not the kind of // expression that we want to analyze return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression && // nameof(System.Void) isn't allowed in C#. typeofExpression is not { Type: PredefinedTypeSyntax { Keyword: { RawKind: (int)SyntaxKind.VoidKeyword } } }; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal abstract partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> : IMoveDeclarationNearReferenceService where TService : AbstractMoveDeclarationNearReferenceService<TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> where TStatementSyntax : SyntaxNode where TLocalDeclarationStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { protected abstract bool IsMeaningfulBlock(SyntaxNode node); protected abstract bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock); protected abstract SyntaxNode GetVariableDeclaratorSymbolNode(TVariableDeclaratorSyntax variableDeclarator); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract SyntaxToken GetIdentifierOfVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract Task<bool> TypesAreCompatibleAsync(Document document, ILocalSymbol localSymbol, TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken); public async Task<bool> CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, node, cancellationToken).ConfigureAwait(false); return state != null; } private async Task<State> ComputeStateAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { if (!(node is TLocalDeclarationStatementSyntax statement)) { return null; } var state = await State.GenerateAsync((TService)this, document, statement, cancellationToken).ConfigureAwait(false); if (state == null) { return null; } if (state.IndexOfDeclarationStatementInInnermostBlock >= 0 && state.IndexOfDeclarationStatementInInnermostBlock == state.IndexOfFirstStatementAffectedInInnermostBlock - 1 && !await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false)) { // Declaration statement is already closest to the first reference // and they both cannot be merged into a single statement, so bail out. return null; } if (!CanMoveToBlock(state.LocalSymbol, state.OutermostBlock, state.InnermostBlock)) { return null; } return state; } public async Task<Document> MoveDeclarationNearReferenceAsync( Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, localDeclarationStatement, cancellationToken).ConfigureAwait(false); if (state == null) { return document; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var crossesMeaningfulBlock = CrossesMeaningfulBlock(state); var warningAnnotation = crossesMeaningfulBlock ? WarningAnnotation.Create(WorkspaceExtensionsResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning) : null; var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false); if (canMergeDeclarationAndAssignment) { editor.RemoveNode(state.DeclarationStatement); MergeDeclarationAndAssignment( document, state, editor, warningAnnotation); } else { var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count && state.OutermostBlockStatements[statementIndex + 1] == state.FirstStatementAffectedInInnermostBlock) { // Already at the correct location. return document; } editor.RemoveNode(state.DeclarationStatement); await MoveDeclarationToFirstReferenceAsync( document, state, editor, warningAnnotation, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private static async Task MoveDeclarationToFirstReferenceAsync(Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation, CancellationToken cancellationToken) { // If we're not merging with an existing declaration, make the declaration semantically // explicit to improve the chances that it won't break code. var explicitDeclarationStatement = await Simplifier.ExpandAsync( state.DeclarationStatement, document, cancellationToken: cancellationToken).ConfigureAwait(false); // place the declaration above the first statement that references it. var declarationStatement = warningAnnotation == null ? explicitDeclarationStatement : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var newNextStatement = state.FirstStatementAffectedInInnermostBlock; declarationStatement = declarationStatement.WithPrependedLeadingTrivia( syntaxFacts.GetLeadingBlankLines(newNextStatement)); editor.InsertBefore( state.FirstStatementAffectedInInnermostBlock, declarationStatement); editor.ReplaceNode( newNextStatement, newNextStatement.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia( syntaxFacts.GetTriviaAfterLeadingBlankLines(newNextStatement))); // Move leading whitespace from the declaration statement to the next statement. var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count) { var originalNextStatement = state.OutermostBlockStatements[statementIndex + 1]; editor.ReplaceNode( originalNextStatement, (current, generator) => current.WithAdditionalAnnotations(Formatter.Annotation).WithPrependedLeadingTrivia( syntaxFacts.GetLeadingBlankLines(state.DeclarationStatement))); } } private static void MergeDeclarationAndAssignment( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation) { // Replace the first reference with a new declaration. var declarationStatement = CreateMergedDeclarationStatement(document, state); declarationStatement = warningAnnotation == null ? declarationStatement : declarationStatement.WithAdditionalAnnotations(warningAnnotation); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); declarationStatement = declarationStatement.WithLeadingTrivia( GetMergedTrivia(syntaxFacts, state.DeclarationStatement, state.FirstStatementAffectedInInnermostBlock)); editor.ReplaceNode( state.FirstStatementAffectedInInnermostBlock, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation)); } private static ImmutableArray<SyntaxTrivia> GetMergedTrivia( ISyntaxFactsService syntaxFacts, TStatementSyntax statement1, TStatementSyntax statement2) { return syntaxFacts.GetLeadingBlankLines(statement2).Concat( syntaxFacts.GetTriviaAfterLeadingBlankLines(statement1)).Concat( syntaxFacts.GetTriviaAfterLeadingBlankLines(statement2)); } private bool CrossesMeaningfulBlock(State state) { var blocks = state.InnermostBlock.GetAncestorsOrThis<SyntaxNode>(); foreach (var block in blocks) { if (block == state.OutermostBlock) { break; } if (IsMeaningfulBlock(block)) { return true; } } return false; } private async Task<bool> CanMergeDeclarationAndAssignmentAsync( Document document, State state, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(state.VariableDeclarator); if (initializer == null || syntaxFacts.IsLiteralExpression(syntaxFacts.GetValueOfEqualsValueClause(initializer))) { var firstStatement = state.FirstStatementAffectedInInnermostBlock; if (syntaxFacts.IsSimpleAssignmentStatement(firstStatement)) { syntaxFacts.GetPartsOfAssignmentStatement(firstStatement, out var left, out var right); if (syntaxFacts.IsIdentifierName(left)) { var localSymbol = state.LocalSymbol; var name = syntaxFacts.GetIdentifierOfSimpleName(left).ValueText; if (syntaxFacts.StringComparer.Equals(name, localSymbol.Name)) { return await TypesAreCompatibleAsync( document, localSymbol, state.DeclarationStatement, right, cancellationToken).ConfigureAwait(false); } } } } return false; } private static TLocalDeclarationStatementSyntax CreateMergedDeclarationStatement( Document document, State state) { var generator = document.GetLanguageService<SyntaxGeneratorInternal>(); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfAssignmentStatement( state.FirstStatementAffectedInInnermostBlock, out var _, out var operatorToken, out var right); return state.DeclarationStatement.ReplaceNode( state.VariableDeclarator, generator.WithInitializer( state.VariableDeclarator.WithoutTrailingTrivia(), generator.EqualsValueClause(operatorToken, right)) .WithTrailingTrivia(state.VariableDeclarator.GetTrailingTrivia())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal abstract partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> : IMoveDeclarationNearReferenceService where TService : AbstractMoveDeclarationNearReferenceService<TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> where TStatementSyntax : SyntaxNode where TLocalDeclarationStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { protected abstract bool IsMeaningfulBlock(SyntaxNode node); protected abstract bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock); protected abstract SyntaxNode GetVariableDeclaratorSymbolNode(TVariableDeclaratorSyntax variableDeclarator); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract SyntaxToken GetIdentifierOfVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract Task<bool> TypesAreCompatibleAsync(Document document, ILocalSymbol localSymbol, TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken); public async Task<bool> CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, node, cancellationToken).ConfigureAwait(false); return state != null; } private async Task<State> ComputeStateAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { if (!(node is TLocalDeclarationStatementSyntax statement)) { return null; } var state = await State.GenerateAsync((TService)this, document, statement, cancellationToken).ConfigureAwait(false); if (state == null) { return null; } if (state.IndexOfDeclarationStatementInInnermostBlock >= 0 && state.IndexOfDeclarationStatementInInnermostBlock == state.IndexOfFirstStatementAffectedInInnermostBlock - 1 && !await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false)) { // Declaration statement is already closest to the first reference // and they both cannot be merged into a single statement, so bail out. return null; } if (!CanMoveToBlock(state.LocalSymbol, state.OutermostBlock, state.InnermostBlock)) { return null; } return state; } public async Task<Document> MoveDeclarationNearReferenceAsync( Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, localDeclarationStatement, cancellationToken).ConfigureAwait(false); if (state == null) { return document; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var crossesMeaningfulBlock = CrossesMeaningfulBlock(state); var warningAnnotation = crossesMeaningfulBlock ? WarningAnnotation.Create(WorkspaceExtensionsResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning) : null; var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false); if (canMergeDeclarationAndAssignment) { editor.RemoveNode(state.DeclarationStatement); MergeDeclarationAndAssignment( document, state, editor, warningAnnotation); } else { var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count && state.OutermostBlockStatements[statementIndex + 1] == state.FirstStatementAffectedInInnermostBlock) { // Already at the correct location. return document; } editor.RemoveNode(state.DeclarationStatement); await MoveDeclarationToFirstReferenceAsync( document, state, editor, warningAnnotation, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private static async Task MoveDeclarationToFirstReferenceAsync(Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation, CancellationToken cancellationToken) { // If we're not merging with an existing declaration, make the declaration semantically // explicit to improve the chances that it won't break code. var explicitDeclarationStatement = await Simplifier.ExpandAsync( state.DeclarationStatement, document, cancellationToken: cancellationToken).ConfigureAwait(false); // place the declaration above the first statement that references it. var declarationStatement = warningAnnotation == null ? explicitDeclarationStatement : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var newNextStatement = state.FirstStatementAffectedInInnermostBlock; declarationStatement = declarationStatement.WithPrependedLeadingTrivia( syntaxFacts.GetLeadingBlankLines(newNextStatement)); editor.InsertBefore( state.FirstStatementAffectedInInnermostBlock, declarationStatement); editor.ReplaceNode( newNextStatement, newNextStatement.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia( syntaxFacts.GetTriviaAfterLeadingBlankLines(newNextStatement))); // Move leading whitespace from the declaration statement to the next statement. var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count) { var originalNextStatement = state.OutermostBlockStatements[statementIndex + 1]; editor.ReplaceNode( originalNextStatement, (current, generator) => current.WithAdditionalAnnotations(Formatter.Annotation).WithPrependedLeadingTrivia( syntaxFacts.GetLeadingBlankLines(state.DeclarationStatement))); } } private static void MergeDeclarationAndAssignment( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation) { // Replace the first reference with a new declaration. var declarationStatement = CreateMergedDeclarationStatement(document, state); declarationStatement = warningAnnotation == null ? declarationStatement : declarationStatement.WithAdditionalAnnotations(warningAnnotation); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); declarationStatement = declarationStatement.WithLeadingTrivia( GetMergedTrivia(syntaxFacts, state.DeclarationStatement, state.FirstStatementAffectedInInnermostBlock)); editor.ReplaceNode( state.FirstStatementAffectedInInnermostBlock, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation)); } private static ImmutableArray<SyntaxTrivia> GetMergedTrivia( ISyntaxFactsService syntaxFacts, TStatementSyntax statement1, TStatementSyntax statement2) { return syntaxFacts.GetLeadingBlankLines(statement2).Concat( syntaxFacts.GetTriviaAfterLeadingBlankLines(statement1)).Concat( syntaxFacts.GetTriviaAfterLeadingBlankLines(statement2)); } private bool CrossesMeaningfulBlock(State state) { var blocks = state.InnermostBlock.GetAncestorsOrThis<SyntaxNode>(); foreach (var block in blocks) { if (block == state.OutermostBlock) { break; } if (IsMeaningfulBlock(block)) { return true; } } return false; } private async Task<bool> CanMergeDeclarationAndAssignmentAsync( Document document, State state, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(state.VariableDeclarator); if (initializer == null || syntaxFacts.IsLiteralExpression(syntaxFacts.GetValueOfEqualsValueClause(initializer))) { var firstStatement = state.FirstStatementAffectedInInnermostBlock; if (syntaxFacts.IsSimpleAssignmentStatement(firstStatement)) { syntaxFacts.GetPartsOfAssignmentStatement(firstStatement, out var left, out var right); if (syntaxFacts.IsIdentifierName(left)) { var localSymbol = state.LocalSymbol; var name = syntaxFacts.GetIdentifierOfSimpleName(left).ValueText; if (syntaxFacts.StringComparer.Equals(name, localSymbol.Name)) { return await TypesAreCompatibleAsync( document, localSymbol, state.DeclarationStatement, right, cancellationToken).ConfigureAwait(false); } } } } return false; } private static TLocalDeclarationStatementSyntax CreateMergedDeclarationStatement( Document document, State state) { var generator = document.GetLanguageService<SyntaxGeneratorInternal>(); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfAssignmentStatement( state.FirstStatementAffectedInInnermostBlock, out var _, out var operatorToken, out var right); return state.DeclarationStatement.ReplaceNode( state.VariableDeclarator, generator.WithInitializer( state.VariableDeclarator.WithoutTrailingTrivia(), generator.EqualsValueClause(operatorToken, right)) .WithTrailingTrivia(state.VariableDeclarator.GetTrailingTrivia())); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EventTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EventSymbolTests Inherits BasicTestBase <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub IlEventVisibility() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit A { .method assembly hidebysig newslot specialname virtual instance void add_E(class [mscorlib]System.Action`1<int32> 'value') cil managed { ret } .method public hidebysig newslot specialname virtual instance void remove_E(class [mscorlib]System.Action`1<int32> 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .event class [mscorlib]System.Action`1<int32> E { .addon instance void A::add_E(class [mscorlib]System.Action`1<int32>) .removeon instance void A::remove_E(class [mscorlib]System.Action`1<int32>) } }]]> Dim vbSource = <compilation name="F"> <file name="F.vb"> Class B Inherits A Sub M() AddHandler E, Nothing RemoveHandler E, Nothing AddHandler MyBase.E, Nothing RemoveHandler MyBase.E, Nothing End Sub End Class </file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.DebugDll) CompilationUtils.AssertTheseCompileDiagnostics(comp1, <Expected> BC30390: 'A.Friend Overridable Overloads AddHandler Event E(value As Action(Of Integer))' is not accessible in this context because it is 'Friend'. AddHandler E, Nothing ~ BC30390: 'A.Friend Overridable Overloads AddHandler Event E(value As Action(Of Integer))' is not accessible in this context because it is 'Friend'. AddHandler MyBase.E, Nothing ~~~~~~~~ </Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub CustomEventVisibility() Dim source = <compilation name="F"> <file name="F.vb"> Imports System Public Class C Protected Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) Console.Write("add") End AddHandler RemoveHandler(ByVal value As EventHandler) Console.Write("remove") End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Console.Write("raise") End RaiseEvent End Event End Class Public Class D Inherits C Public Sub F() AddHandler Click, Nothing RemoveHandler Click, Nothing AddHandler MyBase.Click, Nothing RemoveHandler MyBase.Click, Nothing End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(comp, <Expected></Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub ProtectedHandlerDefinedInCSharp() Dim csharpCompilation = CreateCSharpCompilation(" public class C { protected delegate void Handle(); protected event Handle MyEvent; } public class D: C { public D() { MyEvent += () => {}; } } ") Dim source = Parse(" Public Class E Inherits C Public Sub S() AddHandler MyBase.MyEvent, Nothing End Sub End Class ") Dim vbCompilation = CompilationUtils.CreateCompilationWithMscorlib45AndVBRuntime( source:={source}, references:={csharpCompilation.EmitToImageReference()}, options:=TestOptions.DebugDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(vbCompilation, <Expected></Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub EventVisibility() Dim source = <compilation name="F"> <file name="F.vb"> Public Class Form1 Protected Event EventA As System.Action Private Event EventB As System.Action Friend Event EventC As System.Action End Class Public Class Form2 Inherits Form1 Public Sub New() AddHandler MyBase.EventA, Nothing RemoveHandler MyBase.EventA, Nothing AddHandler EventA, Nothing RemoveHandler EventA, Nothing AddHandler MyBase.EventB, Nothing RemoveHandler MyBase.EventB, Nothing AddHandler EventB, Nothing RemoveHandler EventB, Nothing AddHandler MyBase.EventC, Nothing RemoveHandler MyBase.EventC, Nothing AddHandler EventC, Nothing RemoveHandler EventC, Nothing End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(comp, <Expected> BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. AddHandler MyBase.EventB, Nothing ~~~~~~~~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. RemoveHandler MyBase.EventB, Nothing ~~~~~~~~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. AddHandler EventB, Nothing ~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. RemoveHandler EventB, Nothing ~~~~~~ </Expected>) End Sub <WorkItem(542806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542806")> <Fact()> Public Sub EmptyCustomEvent() Dim source = <compilation name="F"> <file name="F.vb"> Class C Public Custom Event Goo End Class </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseParseDiagnostics(comp2, <expected> BC31122: 'Custom' modifier is not valid on events declared without explicit delegate types. Public Custom Event Goo ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(542891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542891")> <Fact()> Public Sub InterfaceImplements() Dim source = <compilation name="F"> <file name="F.vb"> Imports System.ComponentModel Class C Implements INotifyPropertyChanged Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged End Class </file> </compilation> Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off)) CompilationUtils.AssertNoErrors(comp1) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) End Sub <Fact()> Public Sub RaiseBaseEventedFromDerivedNestedTypes() Dim source = <compilation> <file name="filename.vb"> Module Program Sub Main() End Sub End Module Class C1 Event HelloWorld Class C2 Inherits C1 Sub t RaiseEvent HelloWorld End Sub End Class End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics() End Sub <Fact()> Public Sub MultipleInterfaceImplements() Dim source = <compilation> <file name="filename.vb"> Option Infer On Imports System Imports System.Collections.Generic Interface I Event E As Action(Of Integer) Event E2 As Action(Of String) End Interface Interface I2 Event E As Action(Of Integer) Event E2 As Action(Of String) End Interface Class Base Implements I Implements I2 Event E2(x As Integer) Implements I.E, I2.E Dim eventsList As List(Of Action(Of String)) = New List(Of Action(Of String)) Public Custom Event E As Action(Of String) Implements I.E2, I2.E2 AddHandler(e As Action(Of String)) Console.Write("Add E|") eventsList.Add(e) End AddHandler RemoveHandler(e As Action(Of String)) Console.Write("Remove E|") eventsList.Remove(e) End RemoveHandler RaiseEvent() Dim x As String = Nothing Console.Write("Raise E|") For Each ev In eventsList ev(x) Next End RaiseEvent End Event Sub R RaiseEvent E End Sub End Class Module Module1 Sub Main(args As String()) Dim b = New Base Dim a As Action(Of String) = Sub(x) Console.Write("Added from Base|") End Sub AddHandler b.E, a Dim i_1 As I = b Dim i_2 As I2 = b RemoveHandler i_1.E2, a AddHandler i_2.E2, Sub(x) Console.Write("Added from I2|") End Sub b.R End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[Add E|Remove E|Add E|Raise E|Added from I2|]]>.Value ) End Sub <WorkItem(543309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543309")> <Fact()> Public Sub EventSyntheticDelegateShadows() Dim source = <compilation name="F"> <file name="F.vb"> Public MustInherit Class GameLauncher Public Event Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Shadows Event Empty() End Class </file> </compilation> Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off)) CompilationUtils.AssertNoErrors(comp1) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) End Sub <Fact()> Public Sub EventNoShadows() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public Event Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Event Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40004: event 'Empty' conflicts with event 'Empty' in the base class 'GameLauncher' and should be declared 'Shadows'. Public Event Empty() ~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventAutoPropShadows() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public Event _Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Property EmptyEventhandler As Integer End Class Public MustInherit Class GameLauncher1 Public Property EmptyEventhandler As Integer End Class Public Class MissileLauncher1 Inherits GameLauncher1 Public Event _Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40018: property 'EmptyEventhandler' implicitly declares '_EmptyEventhandler', which conflicts with a member implicitly declared for event '_Empty' in the base class 'GameLauncher'. property should be declared 'Shadows'. Public Property EmptyEventhandler As Integer ~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventAutoPropClash() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public Class MissileLauncher1 Public Event _Empty() Public Property EmptyEventhandler As Integer End Class Public Class MissileLauncher2 Public Property EmptyEventhandler As Integer Public Event _Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> BC31059: event '_Empty' implicitly defines '_EmptyEventHandler', which conflicts with a member implicitly declared for property 'EmptyEventhandler' in class 'MissileLauncher1'. Public Event _Empty() ~~~~~~ BC31059: event '_Empty' implicitly defines '_EmptyEventHandler', which conflicts with a member implicitly declared for property 'EmptyEventhandler' in class 'MissileLauncher2'. Public Event _Empty() ~~~~~~ </expected>) End Sub <Fact()> Public Sub EventNoShadows1() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public EmptyEventHandler as integer End Class Public Class MissileLauncher Inherits GameLauncher Public Event Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40012: event 'Empty' implicitly declares 'EmptyEventHandler', which conflicts with a member in the base class 'GameLauncher', and so the event should be declared 'Shadows'. Public Event Empty() ~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventsAreNotValues() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Class cls1 Event e1() Event e2() Sub goo() System.Console.WriteLine(e1) System.Console.WriteLine(e1 + (e2)) End Sub End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC32022: 'Public Event e1()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1) ~~ BC32022: 'Public Event e1()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1 + (e2)) ~~ BC32022: 'Public Event e2()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1 + (e2)) ~~ ]]> </expected>) End Sub <Fact()> Public Sub EventImplementsInInterfaceAndModule() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Interface I1 Event e1() End Interface Interface I2 Inherits I1 Event e2() Implements I1.e1 End Interface Module m1 Event e2() Implements I1.e1 End Module ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30688: Events in interfaces cannot be declared 'Implements'. Event e2() Implements I1.e1 ~~~~~~~~~~ BC31083: Members in a Module cannot implement interface members. Event e2() Implements I1.e1 ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub AttributesInapplicable() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Imports System Class cls0 <System.ParamArray()> Event RegularEvent() <System.ParamArray()> Custom Event CustomEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30662: Attribute 'ParamArrayAttribute' cannot be applied to 'RegularEvent' because the attribute is not valid on this declaration type. <System.ParamArray()> ~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ParamArrayAttribute' cannot be applied to 'CustomEvent' because the attribute is not valid on this declaration type. <System.ParamArray()> ~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub AttributesApplicable() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Imports System Class cls0 <Obsolete> Event RegularEvent() <Obsolete> Custom Event CustomEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) Dim attributeValidatorSource = Sub(m As ModuleSymbol) ' Event should have an Obsolete attribute Dim type = DirectCast(m.GlobalNamespace.GetMember("cls0"), NamedTypeSymbol) Dim member = type.GetMember("RegularEvent") Dim attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("RegularEventEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("RegularEventEventHandler") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("add_RegularEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_RegularEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) ' Event should have an Obsolete attribute member = type.GetMember("CustomEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("add_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("raise_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) End Sub ' metadata verifier excludes private members as those are not loaded. Dim attributeValidatorMetadata = Sub(m As ModuleSymbol) ' Event should have an Obsolete attribute Dim type = DirectCast(m.GlobalNamespace.GetMember("cls0"), NamedTypeSymbol) Dim member = type.GetMember("RegularEvent") Dim attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not 'member = type.GetMember("RegularEventEvent") 'attrs = member.GetAttributes() 'Assert.Equal(0, attrs.Count) member = type.GetMember("RegularEventEventHandler") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("add_RegularEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CompilerGeneratedAttribute", attrs(0).AttributeClass.Name) member = type.GetMember("remove_RegularEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CompilerGeneratedAttribute", attrs(0).AttributeClass.Name) ' Event should have an Obsolete attribute member = type.GetMember("CustomEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("add_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) 'member = type.GetMember("raise_CustomEvent") 'attrs = member.GetAttributes() 'Assert.Equal(0, attrs.Count) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidatorSource, symbolValidator:=attributeValidatorMetadata) End Sub <WorkItem(543321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543321")> <Fact()> Public Sub DeclareEventWithArgument() CompileAndVerify( <compilation name="DeclareEventWithArgument"> <file name="a.vb"> Class Test Public Event Percent(ByVal Percent1 As Single) Public Shared Sub Main() End Sub End Class </file> </compilation>) End Sub <WorkItem(543366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543366")> <Fact()> Public Sub UseEventDelegateType() CompileAndVerify( <compilation name="DeclareEventWithArgument"> <file name="a.vb"> Class C Event Hello() End Class Module Program Sub Main(args As String()) Dim cc As C = New C Dim a As C.HelloEventHandler = AddressOf Handler AddHandler cc.Hello, a End Sub Sub Handler() End Sub End Module </file> </compilation>) End Sub <WorkItem(543372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543372")> <Fact()> Public Sub AddHandlerWithoutAddressOf() Dim source = <compilation name="F"> <file name="F.vb"> Class C Event Hello() End Class Module Program Sub Goo() End Sub Sub Main(args As String()) Dim x As C AddHandler x.Hello, Goo End Sub End Module </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. AddHandler x.Hello, Goo ~ BC30491: Expression does not produce a value. AddHandler x.Hello, Goo ~~~ </expected>) End Sub <Fact()> Public Sub EventPrivateAccessor() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit ClassLibrary1.Class1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E1 .method private hidebysig specialname instance void add_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::add_E1 .method public hidebysig specialname instance void remove_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::remove_E1 .method public hidebysig instance void Raise(int32 x) cil managed { // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: callvirt instance void [mscorlib]System.Action::Invoke() IL_000b: ret } // end of method Class1::Raise .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor .event [mscorlib]System.Action E1 { .addon instance void ClassLibrary1.Class1::add_E1(class [mscorlib]System.Action) .removeon instance void ClassLibrary1.Class1::remove_E1(class [mscorlib]System.Action) } // end of event Class1::E1 } // end of class ClassLibrary1.Class1 ]]> Dim vbSource = <compilation name="PublicParameterlessConstructorInMetadata_Private"> <file name="a.vb"> Class Program Sub Main() Dim x = New ClassLibrary1.Class1 Dim h as System.Action = Sub() System.Console.WriteLine("hello") AddHandler x.E1, h RemoveHandler x.E1, h x.Raise(1) End Sub End Class </file> </compilation> Dim comp2 = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30456: 'E1' is not a member of 'Class1'. AddHandler x.E1, h ~~~~ BC30456: 'E1' is not a member of 'Class1'. RemoveHandler x.E1, h ~~~~ ]]> </expected>) End Sub <Fact> Public Sub EventProtectedAccessor() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit ClassLibrary1.Class1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E1 .method public hidebysig specialname instance void add_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::add_E1 .method family hidebysig specialname instance void remove_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::remove_E1 .method public hidebysig instance void Raise(int32 x) cil managed { // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: callvirt instance void [mscorlib]System.Action::Invoke() IL_000b: ret } // end of method Class1::Raise .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor .event [mscorlib]System.Action E1 { .addon instance void ClassLibrary1.Class1::add_E1(class [mscorlib]System.Action) .removeon instance void ClassLibrary1.Class1::remove_E1(class [mscorlib]System.Action) } // end of event Class1::E1 } // end of class ClassLibrary1.Class1 ]]> Dim vbSource = <compilation name="PublicParameterlessConstructorInMetadata_Private"> <file name="a.vb"> Class Program Sub Main() Dim x = New ClassLibrary1.Class1 Dim h as System.Action = Sub() System.Console.WriteLine("hello") AddHandler x.E1, h RemoveHandler x.E1, h x.Raise(1) End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30390: 'Class1.Protected Overloads RemoveHandler Event E1(value As Action)' is not accessible in this context because it is 'Protected'. RemoveHandler x.E1, h ~~~~ </expected>) End Sub ' Check that both errors are reported <WorkItem(543504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543504")> <Fact()> Public Sub TestEventWithParamArray() Dim source = <compilation name="TestEventWithParamArray"> <file name="a.vb"> <![CDATA[ Class A Event E1(paramarray o() As object) Delegate Sub d(paramarray o() As object) End Class Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ParamArrayIllegal1, "paramarray").WithArguments("Event"), Diagnostic(ERRID.ERR_ParamArrayIllegal1, "paramarray").WithArguments("Delegate")) End Sub 'import abstract class with abstract event and attempt to override the event <Fact()> Public Sub EventOverridingAndInterop() Dim ilSource = <![CDATA[ // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi beforefieldinit AbsEvent extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: br.s IL_0008 IL_0008: ret } // end of method AbsEvent::.ctor .method public hidebysig newslot specialname abstract virtual instance void add_E(class [mscorlib]System.Action 'value') cil managed { } // end of method AbsEvent::add_E .method public hidebysig newslot specialname abstract virtual instance void remove_E(class [mscorlib]System.Action 'value') cil managed { } // end of method AbsEvent::remove_E .event [mscorlib]System.Action E { .addon instance void AbsEvent::add_E(class [mscorlib]System.Action) .removeon instance void AbsEvent::remove_E(class [mscorlib]System.Action) } // end of event AbsEvent::E } // end of class AbsEvent ]]> Dim vbSource = <compilation> <file name="b.vb"> Class B Inherits AbsEvent Overrides Public Event E As System.Action End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithCustomILSource(vbSource, ilSource) AssertTheseDiagnostics(comp, <expected> BC31499: 'Public MustOverride Event E As Action' is a MustOverride event in the base class 'AbsEvent'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'B' MustInherit. Class B ~ BC30243: 'Overrides' is not valid on an event declaration. Overrides Public Event E As System.Action ~~~~~~~~~ BC40004: event 'E' conflicts with event 'E' in the base class 'AbsEvent' and should be declared 'Shadows'. Overrides Public Event E As System.Action ~ </expected>) End Sub <WorkItem(529772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529772")> <Fact> Public Sub Bug529772_ReproSteps() Dim csCompilation = CreateCSharpCompilation(" using System; namespace AbstEvent { public abstract class Base { public abstract event EventHandler AnEvent; public abstract void method(); public event EventHandler AnotherEvent; } public class base1 : Base { public override event EventHandler AnEvent; public override void method() { } } public abstract class base2 : Base { public override void method() { } } public abstract class GenBase<T> { public abstract event EventHandler AnEvent; } }", assemblyName:="AbstEvent", referencedAssemblies:={MscorlibRef}) Dim vbCompilation = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="App.vb"> Imports AbstEvent Module Module1 Sub Main() End Sub ' Expect compiler catch that Goo1 does not implement AnEvent or method() Class Goo1 Inherits Base End Class ' Expect compiler catch Goo2 does not implement AnEvent Class Goo2 Inherits Base Public Overrides Sub method() End Sub End Class ' Expect compiler catch that Goo3 does not implement AnEvent Class Goo3 Inherits base2 End Class ' Expect no compiler error Class Goo4 Inherits base1 End Class ' Expect no compiler error, since both Goo5 and base2 are abstract MustInherit Class Goo5 Inherits base2 End Class ' ' Testing Type Parameter Printing ' Class GenGoo1(Of T) Inherits GenBase(Of T) End Class Class GenGoo2 Inherits GenBase(Of Integer) End Class MustInherit Class Goo6 Inherits base2 Shadows Public AnEvent As Integer End Class End Module </file> </compilation>, references:={csCompilation.EmitToImageReference()}) vbCompilation.AssertTheseDiagnostics(<errors> BC30610: Class 'Goo1' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Base: Public MustOverride Overloads Sub method(). Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo1' MustInherit. Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo2' MustInherit. Class Goo2 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo3' MustInherit. Class Goo3 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of T)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo1' MustInherit. Class GenGoo1(Of T) ~~~~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of Integer)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo2' MustInherit. Class GenGoo2 ~~~~~~~ BC31404: 'Public AnEvent As Integer' cannot shadow a method declared 'MustOverride'. Shadows Public AnEvent As Integer ~~~~~~~ </errors>) End Sub <WorkItem(529772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529772")> <Fact> Public Sub Bug529772_ReproStepsWithILSource() Dim ilSource = " .class public abstract auto ansi beforefieldinit AbstEvent.Base extends [mscorlib]System.Object { .field private class [mscorlib]System.EventHandler AnotherEvent .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig newslot specialname abstract virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot specialname abstract virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot abstract virtual instance void 'method'() { } .method public hidebysig specialname instance void add_AnotherEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig specialname instance void remove_AnotherEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.Base::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.Base::remove_AnEvent(class [mscorlib]System.EventHandler) } .event [mscorlib]System.EventHandler AnotherEvent { .addon instance void AbstEvent.Base::add_AnotherEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.Base::remove_AnotherEvent(class [mscorlib]System.EventHandler) } } .class public auto ansi beforefieldinit AbstEvent.base1 extends AbstEvent.Base { .field private class [mscorlib]System.EventHandler AnEvent .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig specialname virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig virtual instance void 'method'() { ret } .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.base1::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.base1::remove_AnEvent(class [mscorlib]System.EventHandler) } } .class public abstract auto ansi beforefieldinit AbstEvent.base2 extends AbstEvent.Base { .method public hidebysig virtual instance void 'method'() { ret } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } } .class public abstract auto ansi beforefieldinit AbstEvent.GenBase`1<T> extends [mscorlib]System.Object { .method public hidebysig newslot specialname abstract virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot specialname abstract virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.GenBase`1::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.GenBase`1::remove_AnEvent(class [mscorlib]System.EventHandler) } }" Dim vbSource = <compilation> <file name="App.vb"> Imports AbstEvent Module Module1 Sub Main() End Sub ' Expect compiler catch that Goo1 does not implement AnEvent or method() Class Goo1 Inherits Base End Class ' Expect compiler catch Goo2 does not implement AnEvent Class Goo2 Inherits Base Public Overrides Sub method() End Sub End Class ' Expect compiler catch that Goo3 does not implement AnEvent Class Goo3 Inherits base2 End Class ' Expect no compiler error Class Goo4 Inherits base1 End Class ' Expect no compiler error, since both Goo5 and base2 are abstract MustInherit Class Goo5 Inherits base2 End Class ' ' Testing Type Parameter Printing ' Class GenGoo1(Of T) Inherits GenBase(Of T) End Class Class GenGoo2 Inherits GenBase(Of Integer) End Class MustInherit Class Goo6 Inherits base2 Shadows Public AnEvent As Integer End Class End Module </file> </compilation> Dim vbCompilation = CreateCompilationWithCustomILSource(vbSource, ilSource, includeVbRuntime:=True) vbCompilation.AssertTheseDiagnostics(<errors> BC30610: Class 'Goo1' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Base: Public MustOverride Overloads Sub method(). Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo1' MustInherit. Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo2' MustInherit. Class Goo2 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo3' MustInherit. Class Goo3 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of T)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo1' MustInherit. Class GenGoo1(Of T) ~~~~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of Integer)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo2' MustInherit. Class GenGoo2 ~~~~~~~ BC31404: 'Public AnEvent As Integer' cannot shadow a method declared 'MustOverride'. Shadows Public AnEvent As Integer ~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventInGenericTypes() Dim vbSource = <compilation> <file name="filename.vb"> Class A(Of T) Public Event E1(arg As T) Public Event E2 As System.Action(Of T, T) End Class Class B Sub S Dim x = New A(Of String) Dim a = New A(Of String).E1EventHandler(Sub(arg) End Sub) AddHandler x.E1, a AddHandler x.E2, Sub(a1, a2) End Sub End Sub End Class </file> </compilation> CompileAndVerify(vbSource, sourceSymbolValidator:=Sub(moduleSymbol As ModuleSymbol) Dim tA = DirectCast(moduleSymbol.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim tB = DirectCast(moduleSymbol.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim member = tA.GetMember("E1Event") Assert.NotNull(member) Dim delegateTypeMember = DirectCast(tA.GetMember("E1EventHandler"), SynthesizedEventDelegateSymbol) Assert.NotNull(delegateTypeMember) Assert.Equal(delegateTypeMember.AssociatedSymbol, DirectCast(tA.GetMember("E1"), EventSymbol)) End Sub) End Sub <Fact()> Public Sub BindOnRegularEventParams() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Event E(arg1 As Integer, arg2 As String)'BIND:"Integer" End Class Module Program Sub Main(args As String()) End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Int32", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Int32", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindOnEventHandlerAddHandler() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event E End Class Module Program Sub Main(args As String()) Dim x = New C AddHandler x.E, Sub()'BIND:"E" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event C.E()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindOnEventPrivateField() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event E End Class Module Program Sub Main(args As String()) Dim x = New C AddHandler x.EEvent, Sub()'BIND:"EEvent" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("C.EEvent As C.EEventHandler", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543447")> <Fact()> Public Sub BindOnFieldOfRegularEventHandlerType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Dim ev As EEventHandler Event E Sub T ev = Nothing'BIND:"ev" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("C.ev As C.EEventHandler", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543725")> <Fact()> Public Sub SynthesizedEventDelegateSymbolImplicit() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Event E() End Class ]]></file> </compilation>) Dim typeC = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("C").SingleOrDefault(), NamedTypeSymbol) Dim mems = typeC.GetMembers().OrderBy(Function(s) s.ToDisplayString()).Select(Function(s) s) 'Event Delegate Symbol Assert.Equal(TypeKind.Delegate, DirectCast(mems(0), NamedTypeSymbol).TypeKind) Assert.True(mems(0).IsImplicitlyDeclared) Assert.Equal("C.EEventHandler", mems(0).ToDisplayString()) 'Event Backing Field Assert.Equal(SymbolKind.Field, mems(1).Kind) Assert.True(mems(1).IsImplicitlyDeclared) Assert.Equal("Private EEvent As C.EEventHandler", mems(1).ToDisplayString()) ' Source Event Symbol Assert.Equal(SymbolKind.Event, mems(3).Kind) Assert.False(mems(3).IsImplicitlyDeclared) Assert.Equal("Public Event E()", mems(3).ToDisplayString()) ' Add Accessor Assert.Equal(MethodKind.EventAdd, DirectCast(mems(2), MethodSymbol).MethodKind) Assert.True(mems(2).IsImplicitlyDeclared) Assert.Equal("Public AddHandler Event E(obj As C.EEventHandler)", mems(2).ToDisplayString()) 'Remove Accessor Assert.Equal(MethodKind.EventRemove, DirectCast(mems(4), MethodSymbol).MethodKind) Assert.True(mems(4).IsImplicitlyDeclared) Assert.Equal("Public RemoveHandler Event E(obj As C.EEventHandler)", mems(4).ToDisplayString()) End Sub <WorkItem(545200, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545200")> <Fact()> Public Sub TestBadlyFormattedEventCode() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System<Serializable>Class c11 <NonSerialized()> Public Event Start(ByVal sender As Object, ByVal e As EventArgs) <NonSerialized> Dim x As LongEnd Class ]]></file> </compilation>) Dim typeMembers = compilation.SourceModule.GlobalNamespace.GetMembers().OfType(Of TypeSymbol)() Assert.Equal(1, typeMembers.Count) Dim implicitClass = typeMembers.First Assert.True(DirectCast(implicitClass, NamedTypeSymbol).IsImplicitClass) Assert.False(implicitClass.CanBeReferencedByName) Dim classMembers = implicitClass.GetMembers() Assert.Equal(7, classMembers.Length) Dim eventDelegate = classMembers.OfType(Of SynthesizedEventDelegateSymbol)().Single Assert.Equal("StartEventHandler", eventDelegate.Name) End Sub <WorkItem(545221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545221")> <Fact()> Public Sub TestBadlyFormattedCustomEvent() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Partial Class c1 Private Custom Event E1 as AddHandler() End AddHandler End Event Partial Private Sub M(i As Integer) Handles Me.E1'BIND:"E1" End Sub Sub Raise() RaiseEvent E1(1) End Sub Shared Sub Main() Call New c1().Raise() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event c1.E1 As ?", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub ''' <summary> ''' Avoid redundant errors from handlers when ''' a custom event type has errors. ''' </summary> <Fact> <WorkItem(101185, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=101185")> <WorkItem(530406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530406")> Public Sub CustomEventTypeDuplicateErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Custom Event E As D AddHandler(value As D) End AddHandler RemoveHandler(value As D) End RemoveHandler RaiseEvent() End RaiseEvent End Event Private Delegate Sub D() End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30508: 'E' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. Public Custom Event E As D ~ BC30508: 'value' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. AddHandler(value As D) ~ BC30508: 'value' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. RemoveHandler(value As D) ~ ]]></errors>) End Sub <Fact()> Public Sub MissingSystemTypes_Event() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ Interface I Event E As Object End Interface ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Event E As Object ~ BC30002: Type 'System.Object' is not defined. Event E As Object ~~~~~~ BC31044: Events declared with an 'As' clause must have a delegate type. Event E As Object ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MissingSystemTypes_WithEvents() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file name="a.vb"><![CDATA[ Class C WithEvents F As Object End Class ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Class C ~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. Class C ~ BC30002: Type 'System.Void' is not defined. WithEvents F As Object ~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.AccessedThroughPropertyAttribute..ctor' is not defined. WithEvents F As Object ~ BC30002: Type 'System.Object' is not defined. WithEvents F As Object ~~~~~~ ]]></errors>) End Sub <WorkItem(780993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780993")> <Fact()> Public Sub EventInMemberNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Event X As EventHandler End Class ]]></file> </compilation>) Dim typeMembers = compilation.SourceModule.GlobalNamespace.GetMembers().OfType(Of NamedTypeSymbol)() Assert.Equal(1, typeMembers.Count) Dim c = typeMembers.First Dim classMembers = c.MemberNames Assert.Equal(1, classMembers.Count) Assert.Equal("X", classMembers(0)) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event X As System.EventHandler End Class ]]></file> </compilation>) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) compilation.MakeMemberMissing(SpecialMember.System_Delegate__Combine) compilation.MakeMemberMissing(SpecialMember.System_Delegate__Remove) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Combine' is not defined. Event X As System.EventHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Remove' is not defined. Event X As System.EventHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() class C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Class ]]></file> </compilation>, options:=TestOptions.DebugExe) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() Structure C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugExe) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() class C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Class ]]></file> </compilation>, options:=TestOptions.DebugExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.False((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.False((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_05() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() Structure C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAnInterface() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I Event E() Sub M() Handles Me.E End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30270: 'Handles' is not valid on an interface method declaration. Sub M() Handles Me.E ~~~~~~~~~~~~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Equal("Event I.E()", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAStruct() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Structure S Event E() Sub M() Handles Me.E End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30728: Methods declared in structures cannot have 'Handles' clauses. Sub M() Handles Me.E ~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Equal("Event S.E()", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAnEnum() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Enum E1 'Event E() Sub M() Handles Me.E End Sub End Enum ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30185: 'Enum' must end with a matching 'End Enum'. Enum E1 ~~~~~~~ BC30280: Enum 'E1' must contain at least one member. Enum E1 ~~ BC30619: Statement cannot appear within an Enum body. End of Enum assumed. Sub M() Handles Me.E ~~~~~~~~~~~~~~~~~~~~ BC30590: Event 'E' cannot be found. Sub M() Handles Me.E ~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ~~~~~~~~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <WorkItem(9400, "https://github.com/dotnet/roslyn/issues/9400")> <Fact()> Public Sub HandlesNoMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Sub F() Handles MyBase.E End Interface ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC30270: 'Handles' is not valid on an interface method declaration. Sub F() Handles MyBase.E ~~~~~~~~~~~~~~~~ BC30590: Event 'E' cannot be found. Sub F() Handles MyBase.E ~ </expected>) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class A Public Event E1(x As Integer) End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Dim e1EventHandler = compilation.GetTypeByMetadataName("A+E1EventHandler").DelegateInvokeMethod Assert.Same(e1EventHandler.ContainingType, DirectCast(e1EventHandler.ContainingType.AssociatedSymbol, EventSymbol).Type) Assert.True(e1EventHandler.IsImplicitlyDeclared) Assert.True(e1EventHandler.ContainingType.IsImplicitlyDeclared) Assert.Same(e1EventHandler, xSym.ContainingSymbol) Assert.Same(xSym, e1EventHandler.Parameters.First()) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 Delegate Sub D (z As Integer) Event E1 As D End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("I1.D", e1.Type.ToTestDisplayString()) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().ElementAt(1).Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Null(xSym) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics( <expected> BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'I1'. Public Event E1(x As Integer) Implements I1.E1 ~~~~~ </expected>) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("Event A.E1(x As System.Int32)", e1.ToTestDisplayString()) Assert.Equal("A.E1EventHandler", e1.Type.ToTestDisplayString()) Assert.True(e1.Type.IsDelegateType()) Assert.DoesNotContain(e1.Type, a.GetMembers()) Assert.Same(a, e1.Type.ContainingType) Assert.True(e1.Type.IsImplicitlyDeclared) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(xSym.ContainingSymbol.IsImplicitlyDeclared) Assert.Same(e1.Type, xSym.ContainingType) Assert.Same(xSym, xSym.ContainingType.DelegateInvokeMethod.Parameters.First()) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 class E1EventHandler End Class End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics( <expected> BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'I1'. Public Event E1(x As Integer) Implements I1.E1 ~~~~~ </expected>) Dim e1EventHandler = compilation.GetTypeByMetadataName("A+E1EventHandler") Assert.False(e1EventHandler.IsImplicitlyDeclared) Assert.Equal("A.E1EventHandler", e1EventHandler.ToTestDisplayString()) Assert.Null(e1EventHandler.AssociatedSymbol) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("Event A.E1(x As System.Int32)", e1.ToTestDisplayString()) Assert.Equal("A.E1EventHandler", e1.Type.ToTestDisplayString()) Assert.True(e1.Type.IsDelegateType()) Assert.DoesNotContain(e1.Type, a.GetMembers()) Assert.Same(a, e1.Type.ContainingType) Assert.True(e1.Type.IsImplicitlyDeclared) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(xSym.ContainingSymbol.IsImplicitlyDeclared) Assert.Same(e1.Type, xSym.ContainingType) Assert.Same(xSym, xSym.ContainingType.DelegateInvokeMethod.Parameters.First()) 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.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EventSymbolTests Inherits BasicTestBase <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub IlEventVisibility() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit A { .method assembly hidebysig newslot specialname virtual instance void add_E(class [mscorlib]System.Action`1<int32> 'value') cil managed { ret } .method public hidebysig newslot specialname virtual instance void remove_E(class [mscorlib]System.Action`1<int32> 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .event class [mscorlib]System.Action`1<int32> E { .addon instance void A::add_E(class [mscorlib]System.Action`1<int32>) .removeon instance void A::remove_E(class [mscorlib]System.Action`1<int32>) } }]]> Dim vbSource = <compilation name="F"> <file name="F.vb"> Class B Inherits A Sub M() AddHandler E, Nothing RemoveHandler E, Nothing AddHandler MyBase.E, Nothing RemoveHandler MyBase.E, Nothing End Sub End Class </file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.DebugDll) CompilationUtils.AssertTheseCompileDiagnostics(comp1, <Expected> BC30390: 'A.Friend Overridable Overloads AddHandler Event E(value As Action(Of Integer))' is not accessible in this context because it is 'Friend'. AddHandler E, Nothing ~ BC30390: 'A.Friend Overridable Overloads AddHandler Event E(value As Action(Of Integer))' is not accessible in this context because it is 'Friend'. AddHandler MyBase.E, Nothing ~~~~~~~~ </Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub CustomEventVisibility() Dim source = <compilation name="F"> <file name="F.vb"> Imports System Public Class C Protected Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) Console.Write("add") End AddHandler RemoveHandler(ByVal value As EventHandler) Console.Write("remove") End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Console.Write("raise") End RaiseEvent End Event End Class Public Class D Inherits C Public Sub F() AddHandler Click, Nothing RemoveHandler Click, Nothing AddHandler MyBase.Click, Nothing RemoveHandler MyBase.Click, Nothing End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(comp, <Expected></Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub ProtectedHandlerDefinedInCSharp() Dim csharpCompilation = CreateCSharpCompilation(" public class C { protected delegate void Handle(); protected event Handle MyEvent; } public class D: C { public D() { MyEvent += () => {}; } } ") Dim source = Parse(" Public Class E Inherits C Public Sub S() AddHandler MyBase.MyEvent, Nothing End Sub End Class ") Dim vbCompilation = CompilationUtils.CreateCompilationWithMscorlib45AndVBRuntime( source:={source}, references:={csharpCompilation.EmitToImageReference()}, options:=TestOptions.DebugDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(vbCompilation, <Expected></Expected>) End Sub <WorkItem(20335, "https://github.com/dotnet/roslyn/issues/20335")> <Fact()> Public Sub EventVisibility() Dim source = <compilation name="F"> <file name="F.vb"> Public Class Form1 Protected Event EventA As System.Action Private Event EventB As System.Action Friend Event EventC As System.Action End Class Public Class Form2 Inherits Form1 Public Sub New() AddHandler MyBase.EventA, Nothing RemoveHandler MyBase.EventA, Nothing AddHandler EventA, Nothing RemoveHandler EventA, Nothing AddHandler MyBase.EventB, Nothing RemoveHandler MyBase.EventB, Nothing AddHandler EventB, Nothing RemoveHandler EventB, Nothing AddHandler MyBase.EventC, Nothing RemoveHandler MyBase.EventC, Nothing AddHandler EventC, Nothing RemoveHandler EventC, Nothing End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseCompileDiagnostics(comp, <Expected> BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. AddHandler MyBase.EventB, Nothing ~~~~~~~~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. RemoveHandler MyBase.EventB, Nothing ~~~~~~~~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. AddHandler EventB, Nothing ~~~~~~ BC30389: 'Form1.EventB' is not accessible in this context because it is 'Private'. RemoveHandler EventB, Nothing ~~~~~~ </Expected>) End Sub <WorkItem(542806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542806")> <Fact()> Public Sub EmptyCustomEvent() Dim source = <compilation name="F"> <file name="F.vb"> Class C Public Custom Event Goo End Class </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseParseDiagnostics(comp2, <expected> BC31122: 'Custom' modifier is not valid on events declared without explicit delegate types. Public Custom Event Goo ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(542891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542891")> <Fact()> Public Sub InterfaceImplements() Dim source = <compilation name="F"> <file name="F.vb"> Imports System.ComponentModel Class C Implements INotifyPropertyChanged Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged End Class </file> </compilation> Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off)) CompilationUtils.AssertNoErrors(comp1) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) End Sub <Fact()> Public Sub RaiseBaseEventedFromDerivedNestedTypes() Dim source = <compilation> <file name="filename.vb"> Module Program Sub Main() End Sub End Module Class C1 Event HelloWorld Class C2 Inherits C1 Sub t RaiseEvent HelloWorld End Sub End Class End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics() End Sub <Fact()> Public Sub MultipleInterfaceImplements() Dim source = <compilation> <file name="filename.vb"> Option Infer On Imports System Imports System.Collections.Generic Interface I Event E As Action(Of Integer) Event E2 As Action(Of String) End Interface Interface I2 Event E As Action(Of Integer) Event E2 As Action(Of String) End Interface Class Base Implements I Implements I2 Event E2(x As Integer) Implements I.E, I2.E Dim eventsList As List(Of Action(Of String)) = New List(Of Action(Of String)) Public Custom Event E As Action(Of String) Implements I.E2, I2.E2 AddHandler(e As Action(Of String)) Console.Write("Add E|") eventsList.Add(e) End AddHandler RemoveHandler(e As Action(Of String)) Console.Write("Remove E|") eventsList.Remove(e) End RemoveHandler RaiseEvent() Dim x As String = Nothing Console.Write("Raise E|") For Each ev In eventsList ev(x) Next End RaiseEvent End Event Sub R RaiseEvent E End Sub End Class Module Module1 Sub Main(args As String()) Dim b = New Base Dim a As Action(Of String) = Sub(x) Console.Write("Added from Base|") End Sub AddHandler b.E, a Dim i_1 As I = b Dim i_2 As I2 = b RemoveHandler i_1.E2, a AddHandler i_2.E2, Sub(x) Console.Write("Added from I2|") End Sub b.R End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[Add E|Remove E|Add E|Raise E|Added from I2|]]>.Value ) End Sub <WorkItem(543309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543309")> <Fact()> Public Sub EventSyntheticDelegateShadows() Dim source = <compilation name="F"> <file name="F.vb"> Public MustInherit Class GameLauncher Public Event Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Shadows Event Empty() End Class </file> </compilation> Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off)) CompilationUtils.AssertNoErrors(comp1) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) End Sub <Fact()> Public Sub EventNoShadows() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public Event Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Event Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40004: event 'Empty' conflicts with event 'Empty' in the base class 'GameLauncher' and should be declared 'Shadows'. Public Event Empty() ~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventAutoPropShadows() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public Event _Empty() End Class Public Class MissileLauncher Inherits GameLauncher Public Property EmptyEventhandler As Integer End Class Public MustInherit Class GameLauncher1 Public Property EmptyEventhandler As Integer End Class Public Class MissileLauncher1 Inherits GameLauncher1 Public Event _Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40018: property 'EmptyEventhandler' implicitly declares '_EmptyEventhandler', which conflicts with a member implicitly declared for event '_Empty' in the base class 'GameLauncher'. property should be declared 'Shadows'. Public Property EmptyEventhandler As Integer ~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventAutoPropClash() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public Class MissileLauncher1 Public Event _Empty() Public Property EmptyEventhandler As Integer End Class Public Class MissileLauncher2 Public Property EmptyEventhandler As Integer Public Event _Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> BC31059: event '_Empty' implicitly defines '_EmptyEventHandler', which conflicts with a member implicitly declared for property 'EmptyEventhandler' in class 'MissileLauncher1'. Public Event _Empty() ~~~~~~ BC31059: event '_Empty' implicitly defines '_EmptyEventHandler', which conflicts with a member implicitly declared for property 'EmptyEventhandler' in class 'MissileLauncher2'. Public Event _Empty() ~~~~~~ </expected>) End Sub <Fact()> Public Sub EventNoShadows1() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Public MustInherit Class GameLauncher Public EmptyEventHandler as integer End Class Public Class MissileLauncher Inherits GameLauncher Public Event Empty() End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC40012: event 'Empty' implicitly declares 'EmptyEventHandler', which conflicts with a member in the base class 'GameLauncher', and so the event should be declared 'Shadows'. Public Event Empty() ~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub EventsAreNotValues() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Class cls1 Event e1() Event e2() Sub goo() System.Console.WriteLine(e1) System.Console.WriteLine(e1 + (e2)) End Sub End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC32022: 'Public Event e1()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1) ~~ BC32022: 'Public Event e1()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1 + (e2)) ~~ BC32022: 'Public Event e2()' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. System.Console.WriteLine(e1 + (e2)) ~~ ]]> </expected>) End Sub <Fact()> Public Sub EventImplementsInInterfaceAndModule() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Interface I1 Event e1() End Interface Interface I2 Inherits I1 Event e2() Implements I1.e1 End Interface Module m1 Event e2() Implements I1.e1 End Module ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30688: Events in interfaces cannot be declared 'Implements'. Event e2() Implements I1.e1 ~~~~~~~~~~ BC31083: Members in a Module cannot implement interface members. Event e2() Implements I1.e1 ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub AttributesInapplicable() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Imports System Class cls0 <System.ParamArray()> Event RegularEvent() <System.ParamArray()> Custom Event CustomEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30662: Attribute 'ParamArrayAttribute' cannot be applied to 'RegularEvent' because the attribute is not valid on this declaration type. <System.ParamArray()> ~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ParamArrayAttribute' cannot be applied to 'CustomEvent' because the attribute is not valid on this declaration type. <System.ParamArray()> ~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub AttributesApplicable() Dim source = <compilation name="F"> <file name="F.vb"> <![CDATA[ Imports System Class cls0 <Obsolete> Event RegularEvent() <Obsolete> Custom Event CustomEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertNoErrors(comp2) Dim attributeValidatorSource = Sub(m As ModuleSymbol) ' Event should have an Obsolete attribute Dim type = DirectCast(m.GlobalNamespace.GetMember("cls0"), NamedTypeSymbol) Dim member = type.GetMember("RegularEvent") Dim attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("RegularEventEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("RegularEventEventHandler") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("add_RegularEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_RegularEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) ' Event should have an Obsolete attribute member = type.GetMember("CustomEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("add_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("raise_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) End Sub ' metadata verifier excludes private members as those are not loaded. Dim attributeValidatorMetadata = Sub(m As ModuleSymbol) ' Event should have an Obsolete attribute Dim type = DirectCast(m.GlobalNamespace.GetMember("cls0"), NamedTypeSymbol) Dim member = type.GetMember("RegularEvent") Dim attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not 'member = type.GetMember("RegularEventEvent") 'attrs = member.GetAttributes() 'Assert.Equal(0, attrs.Count) member = type.GetMember("RegularEventEventHandler") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("add_RegularEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CompilerGeneratedAttribute", attrs(0).AttributeClass.Name) member = type.GetMember("remove_RegularEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CompilerGeneratedAttribute", attrs(0).AttributeClass.Name) ' Event should have an Obsolete attribute member = type.GetMember("CustomEvent") attrs = member.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("System.ObsoleteAttribute", attrs(0).AttributeClass.ToDisplayString) ' additional synthetic members (field, accessors and such) should not member = type.GetMember("add_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) member = type.GetMember("remove_CustomEvent") attrs = member.GetAttributes() Assert.Equal(0, attrs.Length) 'member = type.GetMember("raise_CustomEvent") 'attrs = member.GetAttributes() 'Assert.Equal(0, attrs.Count) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidatorSource, symbolValidator:=attributeValidatorMetadata) End Sub <WorkItem(543321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543321")> <Fact()> Public Sub DeclareEventWithArgument() CompileAndVerify( <compilation name="DeclareEventWithArgument"> <file name="a.vb"> Class Test Public Event Percent(ByVal Percent1 As Single) Public Shared Sub Main() End Sub End Class </file> </compilation>) End Sub <WorkItem(543366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543366")> <Fact()> Public Sub UseEventDelegateType() CompileAndVerify( <compilation name="DeclareEventWithArgument"> <file name="a.vb"> Class C Event Hello() End Class Module Program Sub Main(args As String()) Dim cc As C = New C Dim a As C.HelloEventHandler = AddressOf Handler AddHandler cc.Hello, a End Sub Sub Handler() End Sub End Module </file> </compilation>) End Sub <WorkItem(543372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543372")> <Fact()> Public Sub AddHandlerWithoutAddressOf() Dim source = <compilation name="F"> <file name="F.vb"> Class C Event Hello() End Class Module Program Sub Goo() End Sub Sub Main(args As String()) Dim x As C AddHandler x.Hello, Goo End Sub End Module </file> </compilation> Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. AddHandler x.Hello, Goo ~ BC30491: Expression does not produce a value. AddHandler x.Hello, Goo ~~~ </expected>) End Sub <Fact()> Public Sub EventPrivateAccessor() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit ClassLibrary1.Class1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E1 .method private hidebysig specialname instance void add_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::add_E1 .method public hidebysig specialname instance void remove_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::remove_E1 .method public hidebysig instance void Raise(int32 x) cil managed { // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: callvirt instance void [mscorlib]System.Action::Invoke() IL_000b: ret } // end of method Class1::Raise .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor .event [mscorlib]System.Action E1 { .addon instance void ClassLibrary1.Class1::add_E1(class [mscorlib]System.Action) .removeon instance void ClassLibrary1.Class1::remove_E1(class [mscorlib]System.Action) } // end of event Class1::E1 } // end of class ClassLibrary1.Class1 ]]> Dim vbSource = <compilation name="PublicParameterlessConstructorInMetadata_Private"> <file name="a.vb"> Class Program Sub Main() Dim x = New ClassLibrary1.Class1 Dim h as System.Action = Sub() System.Console.WriteLine("hello") AddHandler x.E1, h RemoveHandler x.E1, h x.Raise(1) End Sub End Class </file> </compilation> Dim comp2 = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> <![CDATA[ BC30456: 'E1' is not a member of 'Class1'. AddHandler x.E1, h ~~~~ BC30456: 'E1' is not a member of 'Class1'. RemoveHandler x.E1, h ~~~~ ]]> </expected>) End Sub <Fact> Public Sub EventProtectedAccessor() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit ClassLibrary1.Class1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E1 .method public hidebysig specialname instance void add_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::add_E1 .method family hidebysig specialname instance void remove_E1(class [mscorlib]System.Action 'value') cil managed { // Code size 41 (0x29) .maxstack 3 .locals init (class [mscorlib]System.Action V_0, class [mscorlib]System.Action V_1, class [mscorlib]System.Action V_2) IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0010: castclass [mscorlib]System.Action IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.Action>(!!0&, !!0, !!0) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } // end of method Class1::remove_E1 .method public hidebysig instance void Raise(int32 x) cil managed { // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Action ClassLibrary1.Class1::E1 IL_0006: callvirt instance void [mscorlib]System.Action::Invoke() IL_000b: ret } // end of method Class1::Raise .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor .event [mscorlib]System.Action E1 { .addon instance void ClassLibrary1.Class1::add_E1(class [mscorlib]System.Action) .removeon instance void ClassLibrary1.Class1::remove_E1(class [mscorlib]System.Action) } // end of event Class1::E1 } // end of class ClassLibrary1.Class1 ]]> Dim vbSource = <compilation name="PublicParameterlessConstructorInMetadata_Private"> <file name="a.vb"> Class Program Sub Main() Dim x = New ClassLibrary1.Class1 Dim h as System.Action = Sub() System.Console.WriteLine("hello") AddHandler x.E1, h RemoveHandler x.E1, h x.Raise(1) End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30390: 'Class1.Protected Overloads RemoveHandler Event E1(value As Action)' is not accessible in this context because it is 'Protected'. RemoveHandler x.E1, h ~~~~ </expected>) End Sub ' Check that both errors are reported <WorkItem(543504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543504")> <Fact()> Public Sub TestEventWithParamArray() Dim source = <compilation name="TestEventWithParamArray"> <file name="a.vb"> <![CDATA[ Class A Event E1(paramarray o() As object) Delegate Sub d(paramarray o() As object) End Class Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ParamArrayIllegal1, "paramarray").WithArguments("Event"), Diagnostic(ERRID.ERR_ParamArrayIllegal1, "paramarray").WithArguments("Delegate")) End Sub 'import abstract class with abstract event and attempt to override the event <Fact()> Public Sub EventOverridingAndInterop() Dim ilSource = <![CDATA[ // =============== CLASS MEMBERS DECLARATION =================== .class public abstract auto ansi beforefieldinit AbsEvent extends [mscorlib]System.Object { .field private class [mscorlib]System.Action E .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: br.s IL_0008 IL_0008: ret } // end of method AbsEvent::.ctor .method public hidebysig newslot specialname abstract virtual instance void add_E(class [mscorlib]System.Action 'value') cil managed { } // end of method AbsEvent::add_E .method public hidebysig newslot specialname abstract virtual instance void remove_E(class [mscorlib]System.Action 'value') cil managed { } // end of method AbsEvent::remove_E .event [mscorlib]System.Action E { .addon instance void AbsEvent::add_E(class [mscorlib]System.Action) .removeon instance void AbsEvent::remove_E(class [mscorlib]System.Action) } // end of event AbsEvent::E } // end of class AbsEvent ]]> Dim vbSource = <compilation> <file name="b.vb"> Class B Inherits AbsEvent Overrides Public Event E As System.Action End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithCustomILSource(vbSource, ilSource) AssertTheseDiagnostics(comp, <expected> BC31499: 'Public MustOverride Event E As Action' is a MustOverride event in the base class 'AbsEvent'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'B' MustInherit. Class B ~ BC30243: 'Overrides' is not valid on an event declaration. Overrides Public Event E As System.Action ~~~~~~~~~ BC40004: event 'E' conflicts with event 'E' in the base class 'AbsEvent' and should be declared 'Shadows'. Overrides Public Event E As System.Action ~ </expected>) End Sub <WorkItem(529772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529772")> <Fact> Public Sub Bug529772_ReproSteps() Dim csCompilation = CreateCSharpCompilation(" using System; namespace AbstEvent { public abstract class Base { public abstract event EventHandler AnEvent; public abstract void method(); public event EventHandler AnotherEvent; } public class base1 : Base { public override event EventHandler AnEvent; public override void method() { } } public abstract class base2 : Base { public override void method() { } } public abstract class GenBase<T> { public abstract event EventHandler AnEvent; } }", assemblyName:="AbstEvent", referencedAssemblies:={MscorlibRef}) Dim vbCompilation = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="App.vb"> Imports AbstEvent Module Module1 Sub Main() End Sub ' Expect compiler catch that Goo1 does not implement AnEvent or method() Class Goo1 Inherits Base End Class ' Expect compiler catch Goo2 does not implement AnEvent Class Goo2 Inherits Base Public Overrides Sub method() End Sub End Class ' Expect compiler catch that Goo3 does not implement AnEvent Class Goo3 Inherits base2 End Class ' Expect no compiler error Class Goo4 Inherits base1 End Class ' Expect no compiler error, since both Goo5 and base2 are abstract MustInherit Class Goo5 Inherits base2 End Class ' ' Testing Type Parameter Printing ' Class GenGoo1(Of T) Inherits GenBase(Of T) End Class Class GenGoo2 Inherits GenBase(Of Integer) End Class MustInherit Class Goo6 Inherits base2 Shadows Public AnEvent As Integer End Class End Module </file> </compilation>, references:={csCompilation.EmitToImageReference()}) vbCompilation.AssertTheseDiagnostics(<errors> BC30610: Class 'Goo1' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Base: Public MustOverride Overloads Sub method(). Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo1' MustInherit. Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo2' MustInherit. Class Goo2 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo3' MustInherit. Class Goo3 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of T)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo1' MustInherit. Class GenGoo1(Of T) ~~~~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of Integer)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo2' MustInherit. Class GenGoo2 ~~~~~~~ BC31404: 'Public AnEvent As Integer' cannot shadow a method declared 'MustOverride'. Shadows Public AnEvent As Integer ~~~~~~~ </errors>) End Sub <WorkItem(529772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529772")> <Fact> Public Sub Bug529772_ReproStepsWithILSource() Dim ilSource = " .class public abstract auto ansi beforefieldinit AbstEvent.Base extends [mscorlib]System.Object { .field private class [mscorlib]System.EventHandler AnotherEvent .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig newslot specialname abstract virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot specialname abstract virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot abstract virtual instance void 'method'() { } .method public hidebysig specialname instance void add_AnotherEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig specialname instance void remove_AnotherEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.Base::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.Base::remove_AnEvent(class [mscorlib]System.EventHandler) } .event [mscorlib]System.EventHandler AnotherEvent { .addon instance void AbstEvent.Base::add_AnotherEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.Base::remove_AnotherEvent(class [mscorlib]System.EventHandler) } } .class public auto ansi beforefieldinit AbstEvent.base1 extends AbstEvent.Base { .field private class [mscorlib]System.EventHandler AnEvent .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig specialname virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public hidebysig virtual instance void 'method'() { ret } .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.base1::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.base1::remove_AnEvent(class [mscorlib]System.EventHandler) } } .class public abstract auto ansi beforefieldinit AbstEvent.base2 extends AbstEvent.Base { .method public hidebysig virtual instance void 'method'() { ret } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } } .class public abstract auto ansi beforefieldinit AbstEvent.GenBase`1<T> extends [mscorlib]System.Object { .method public hidebysig newslot specialname abstract virtual instance void add_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig newslot specialname abstract virtual instance void remove_AnEvent(class [mscorlib]System.EventHandler 'value') { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) } .method family hidebysig specialname rtspecialname instance void .ctor() { ret } .event [mscorlib]System.EventHandler AnEvent { .addon instance void AbstEvent.GenBase`1::add_AnEvent(class [mscorlib]System.EventHandler) .removeon instance void AbstEvent.GenBase`1::remove_AnEvent(class [mscorlib]System.EventHandler) } }" Dim vbSource = <compilation> <file name="App.vb"> Imports AbstEvent Module Module1 Sub Main() End Sub ' Expect compiler catch that Goo1 does not implement AnEvent or method() Class Goo1 Inherits Base End Class ' Expect compiler catch Goo2 does not implement AnEvent Class Goo2 Inherits Base Public Overrides Sub method() End Sub End Class ' Expect compiler catch that Goo3 does not implement AnEvent Class Goo3 Inherits base2 End Class ' Expect no compiler error Class Goo4 Inherits base1 End Class ' Expect no compiler error, since both Goo5 and base2 are abstract MustInherit Class Goo5 Inherits base2 End Class ' ' Testing Type Parameter Printing ' Class GenGoo1(Of T) Inherits GenBase(Of T) End Class Class GenGoo2 Inherits GenBase(Of Integer) End Class MustInherit Class Goo6 Inherits base2 Shadows Public AnEvent As Integer End Class End Module </file> </compilation> Dim vbCompilation = CreateCompilationWithCustomILSource(vbSource, ilSource, includeVbRuntime:=True) vbCompilation.AssertTheseDiagnostics(<errors> BC30610: Class 'Goo1' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Base: Public MustOverride Overloads Sub method(). Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo1' MustInherit. Class Goo1 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo2' MustInherit. Class Goo2 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.Base'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'Goo3' MustInherit. Class Goo3 ~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of T)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo1' MustInherit. Class GenGoo1(Of T) ~~~~~~~ BC31499: 'Public MustOverride Event AnEvent As EventHandler' is a MustOverride event in the base class 'AbstEvent.GenBase(Of Integer)'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class 'GenGoo2' MustInherit. Class GenGoo2 ~~~~~~~ BC31404: 'Public AnEvent As Integer' cannot shadow a method declared 'MustOverride'. Shadows Public AnEvent As Integer ~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventInGenericTypes() Dim vbSource = <compilation> <file name="filename.vb"> Class A(Of T) Public Event E1(arg As T) Public Event E2 As System.Action(Of T, T) End Class Class B Sub S Dim x = New A(Of String) Dim a = New A(Of String).E1EventHandler(Sub(arg) End Sub) AddHandler x.E1, a AddHandler x.E2, Sub(a1, a2) End Sub End Sub End Class </file> </compilation> CompileAndVerify(vbSource, sourceSymbolValidator:=Sub(moduleSymbol As ModuleSymbol) Dim tA = DirectCast(moduleSymbol.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim tB = DirectCast(moduleSymbol.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim member = tA.GetMember("E1Event") Assert.NotNull(member) Dim delegateTypeMember = DirectCast(tA.GetMember("E1EventHandler"), SynthesizedEventDelegateSymbol) Assert.NotNull(delegateTypeMember) Assert.Equal(delegateTypeMember.AssociatedSymbol, DirectCast(tA.GetMember("E1"), EventSymbol)) End Sub) End Sub <Fact()> Public Sub BindOnRegularEventParams() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Event E(arg1 As Integer, arg2 As String)'BIND:"Integer" End Class Module Program Sub Main(args As String()) End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Int32", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Int32", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindOnEventHandlerAddHandler() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event E End Class Module Program Sub Main(args As String()) Dim x = New C AddHandler x.E, Sub()'BIND:"E" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event C.E()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindOnEventPrivateField() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event E End Class Module Program Sub Main(args As String()) Dim x = New C AddHandler x.EEvent, Sub()'BIND:"EEvent" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("C.EEvent As C.EEventHandler", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543447")> <Fact()> Public Sub BindOnFieldOfRegularEventHandlerType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Dim ev As EEventHandler Event E Sub T ev = Nothing'BIND:"ev" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C.EEventHandler", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("C.EEventHandler", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("C.ev As C.EEventHandler", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543725")> <Fact()> Public Sub SynthesizedEventDelegateSymbolImplicit() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Event E() End Class ]]></file> </compilation>) Dim typeC = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("C").SingleOrDefault(), NamedTypeSymbol) Dim mems = typeC.GetMembers().OrderBy(Function(s) s.ToDisplayString()).Select(Function(s) s) 'Event Delegate Symbol Assert.Equal(TypeKind.Delegate, DirectCast(mems(0), NamedTypeSymbol).TypeKind) Assert.True(mems(0).IsImplicitlyDeclared) Assert.Equal("C.EEventHandler", mems(0).ToDisplayString()) 'Event Backing Field Assert.Equal(SymbolKind.Field, mems(1).Kind) Assert.True(mems(1).IsImplicitlyDeclared) Assert.Equal("Private EEvent As C.EEventHandler", mems(1).ToDisplayString()) ' Source Event Symbol Assert.Equal(SymbolKind.Event, mems(3).Kind) Assert.False(mems(3).IsImplicitlyDeclared) Assert.Equal("Public Event E()", mems(3).ToDisplayString()) ' Add Accessor Assert.Equal(MethodKind.EventAdd, DirectCast(mems(2), MethodSymbol).MethodKind) Assert.True(mems(2).IsImplicitlyDeclared) Assert.Equal("Public AddHandler Event E(obj As C.EEventHandler)", mems(2).ToDisplayString()) 'Remove Accessor Assert.Equal(MethodKind.EventRemove, DirectCast(mems(4), MethodSymbol).MethodKind) Assert.True(mems(4).IsImplicitlyDeclared) Assert.Equal("Public RemoveHandler Event E(obj As C.EEventHandler)", mems(4).ToDisplayString()) End Sub <WorkItem(545200, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545200")> <Fact()> Public Sub TestBadlyFormattedEventCode() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System<Serializable>Class c11 <NonSerialized()> Public Event Start(ByVal sender As Object, ByVal e As EventArgs) <NonSerialized> Dim x As LongEnd Class ]]></file> </compilation>) Dim typeMembers = compilation.SourceModule.GlobalNamespace.GetMembers().OfType(Of TypeSymbol)() Assert.Equal(1, typeMembers.Count) Dim implicitClass = typeMembers.First Assert.True(DirectCast(implicitClass, NamedTypeSymbol).IsImplicitClass) Assert.False(implicitClass.CanBeReferencedByName) Dim classMembers = implicitClass.GetMembers() Assert.Equal(7, classMembers.Length) Dim eventDelegate = classMembers.OfType(Of SynthesizedEventDelegateSymbol)().Single Assert.Equal("StartEventHandler", eventDelegate.Name) End Sub <WorkItem(545221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545221")> <Fact()> Public Sub TestBadlyFormattedCustomEvent() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Partial Class c1 Private Custom Event E1 as AddHandler() End AddHandler End Event Partial Private Sub M(i As Integer) Handles Me.E1'BIND:"E1" End Sub Sub Raise() RaiseEvent E1(1) End Sub Shared Sub Main() Call New c1().Raise() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event c1.E1 As ?", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub ''' <summary> ''' Avoid redundant errors from handlers when ''' a custom event type has errors. ''' </summary> <Fact> <WorkItem(101185, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=101185")> <WorkItem(530406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530406")> Public Sub CustomEventTypeDuplicateErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Custom Event E As D AddHandler(value As D) End AddHandler RemoveHandler(value As D) End RemoveHandler RaiseEvent() End RaiseEvent End Event Private Delegate Sub D() End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30508: 'E' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. Public Custom Event E As D ~ BC30508: 'value' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. AddHandler(value As D) ~ BC30508: 'value' cannot expose type 'C.D' in namespace '<Default>' through class 'C'. RemoveHandler(value As D) ~ ]]></errors>) End Sub <Fact()> Public Sub MissingSystemTypes_Event() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ Interface I Event E As Object End Interface ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Event E As Object ~ BC30002: Type 'System.Object' is not defined. Event E As Object ~~~~~~ BC31044: Events declared with an 'As' clause must have a delegate type. Event E As Object ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MissingSystemTypes_WithEvents() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file name="a.vb"><![CDATA[ Class C WithEvents F As Object End Class ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Class C ~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. Class C ~ BC30002: Type 'System.Void' is not defined. WithEvents F As Object ~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.AccessedThroughPropertyAttribute..ctor' is not defined. WithEvents F As Object ~ BC30002: Type 'System.Object' is not defined. WithEvents F As Object ~~~~~~ ]]></errors>) End Sub <WorkItem(780993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780993")> <Fact()> Public Sub EventInMemberNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Event X As EventHandler End Class ]]></file> </compilation>) Dim typeMembers = compilation.SourceModule.GlobalNamespace.GetMembers().OfType(Of NamedTypeSymbol)() Assert.Equal(1, typeMembers.Count) Dim c = typeMembers.First Dim classMembers = c.MemberNames Assert.Equal(1, classMembers.Count) Assert.Equal("X", classMembers(0)) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Event X As System.EventHandler End Class ]]></file> </compilation>) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) compilation.MakeMemberMissing(SpecialMember.System_Delegate__Combine) compilation.MakeMemberMissing(SpecialMember.System_Delegate__Remove) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Combine' is not defined. Event X As System.EventHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Remove' is not defined. Event X As System.EventHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() class C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Class ]]></file> </compilation>, options:=TestOptions.DebugExe) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() Structure C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugExe) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (E1 V_0, E1 V_1, E1 V_2) IL_0000: ldarg.0 IL_0001: ldfld "C.eEvent As E1" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldarg.1 IL_000b: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_0010: castclass "E1" IL_0015: stloc.2 IL_0016: ldarg.0 IL_0017: ldflda "C.eEvent As E1" IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call "Function System.Threading.Interlocked.CompareExchange(Of E1)(ByRef E1, E1, E1) As E1" IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: ldloc.1 IL_0026: bne.un.s IL_0007 IL_0028: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() class C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Class ]]></file> </compilation>, options:=TestOptions.DebugExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.False((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.False((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) End Sub <Fact, WorkItem(1027568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027568"), WorkItem(528573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528573")> Public Sub MissingCompareExchange_05() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ public delegate sub E1() Structure C public event e As E1 public shared sub Main() Dim v = new C() System.Console.Write(v.eEvent Is Nothing) Addhandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) Removehandler v.e, AddressOf Main System.Console.Write(v.eEvent Is Nothing) End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) Dim verifier = CompileAndVerify(compilation, expectedOutput:="TrueFalseTrue", symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim e = c.GetMember(Of EventSymbol)("e") Dim addMethod = e.AddMethod Assert.True((addMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) Dim removeMethod = e.RemoveMethod Assert.True((removeMethod.ImplementationAttributes And System.Reflection.MethodImplAttributes.Synchronized) = 0) End Sub).VerifyDiagnostics() verifier.VerifyIL("C.add_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Combine(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) verifier.VerifyIL("C.remove_e", <![CDATA[ { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld "C.eEvent As E1" IL_0007: ldarg.1 IL_0008: call "Function System.Delegate.Remove(System.Delegate, System.Delegate) As System.Delegate" IL_000d: castclass "E1" IL_0012: stfld "C.eEvent As E1" IL_0017: ret } ]]>) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAnInterface() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I Event E() Sub M() Handles Me.E End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30270: 'Handles' is not valid on an interface method declaration. Sub M() Handles Me.E ~~~~~~~~~~~~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Equal("Event I.E()", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAStruct() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Structure S Event E() Sub M() Handles Me.E End Sub End Structure ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30728: Methods declared in structures cannot have 'Handles' clauses. Sub M() Handles Me.E ~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Equal("Event S.E()", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(3448, "https://github.com/dotnet/roslyn/issues/3448")> Public Sub HandlesInAnEnum() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Enum E1 'Event E() Sub M() Handles Me.E End Sub End Enum ]]></file> </compilation>, options:=TestOptions.DebugDll) Dim expected = <expected> BC30185: 'Enum' must end with a matching 'End Enum'. Enum E1 ~~~~~~~ BC30280: Enum 'E1' must contain at least one member. Enum E1 ~~ BC30619: Statement cannot appear within an Enum body. End of Enum assumed. Sub M() Handles Me.E ~~~~~~~~~~~~~~~~~~~~ BC30590: Event 'E' cannot be found. Sub M() Handles Me.E ~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ~~~~~~~~ </expected> compilation.AssertTheseDiagnostics(expected) compilation.AssertTheseEmitDiagnostics(expected) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "E").Single() Assert.Equal("Me.E", node.Parent.ToString()) Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <WorkItem(9400, "https://github.com/dotnet/roslyn/issues/9400")> <Fact()> Public Sub HandlesNoMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Sub F() Handles MyBase.E End Interface ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC30270: 'Handles' is not valid on an interface method declaration. Sub F() Handles MyBase.E ~~~~~~~~~~~~~~~~ BC30590: Event 'E' cannot be found. Sub F() Handles MyBase.E ~ </expected>) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class A Public Event E1(x As Integer) End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Dim e1EventHandler = compilation.GetTypeByMetadataName("A+E1EventHandler").DelegateInvokeMethod Assert.Same(e1EventHandler.ContainingType, DirectCast(e1EventHandler.ContainingType.AssociatedSymbol, EventSymbol).Type) Assert.True(e1EventHandler.IsImplicitlyDeclared) Assert.True(e1EventHandler.ContainingType.IsImplicitlyDeclared) Assert.Same(e1EventHandler, xSym.ContainingSymbol) Assert.Same(xSym, e1EventHandler.Parameters.First()) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 Delegate Sub D (z As Integer) Event E1 As D End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("I1.D", e1.Type.ToTestDisplayString()) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().ElementAt(1).Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Null(xSym) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics( <expected> BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'I1'. Public Event E1(x As Integer) Implements I1.E1 ~~~~~ </expected>) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("Event A.E1(x As System.Int32)", e1.ToTestDisplayString()) Assert.Equal("A.E1EventHandler", e1.Type.ToTestDisplayString()) Assert.True(e1.Type.IsDelegateType()) Assert.DoesNotContain(e1.Type, a.GetMembers()) Assert.Same(a, e1.Type.ContainingType) Assert.True(e1.Type.IsImplicitlyDeclared) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(xSym.ContainingSymbol.IsImplicitlyDeclared) Assert.Same(e1.Type, xSym.ContainingType) Assert.Same(xSym, xSym.ContainingType.DelegateInvokeMethod.Parameters.First()) End Sub <WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")> <Fact()> Public Sub SemanticModelOnParameters_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 End Interface Class A Implements I1 Public Event E1(x As Integer) Implements I1.E1 class E1EventHandler End Class End Class]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics( <expected> BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'I1'. Public Event E1(x As Integer) Implements I1.E1 ~~~~~ </expected>) Dim e1EventHandler = compilation.GetTypeByMetadataName("A+E1EventHandler") Assert.False(e1EventHandler.IsImplicitlyDeclared) Assert.Equal("A.E1EventHandler", e1EventHandler.ToTestDisplayString()) Assert.Null(e1EventHandler.AssociatedSymbol) Dim a = compilation.GetTypeByMetadataName("A") Dim e1 = a.GetMember(Of EventSymbol)("E1") Assert.Equal("Event A.E1(x As System.Int32)", e1.ToTestDisplayString()) Assert.Equal("A.E1EventHandler", e1.Type.ToTestDisplayString()) Assert.True(e1.Type.IsDelegateType()) Assert.DoesNotContain(e1.Type, a.GetMembers()) Assert.Same(a, e1.Type.ContainingType) Assert.True(e1.Type.IsImplicitlyDeclared) Dim tree = compilation.SyntaxTrees.Single() Dim x = tree.GetRoot().DescendantNodes().OfType(Of ParameterSyntax)().Single().Identifier Dim model = compilation.GetSemanticModel(tree) Dim xSym = model.GetDeclaredSymbol(x) Assert.Equal("x As System.Int32", xSym.ToTestDisplayString()) Assert.False(xSym.IsImplicitlyDeclared) Assert.Equal("x As Integer", xSym.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(xSym.ContainingSymbol.IsImplicitlyDeclared) Assert.Same(e1.Type, xSym.ContainingType) Assert.Same(xSym, xSym.ContainingType.DelegateInvokeMethod.Parameters.First()) End Sub End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/VisualBasic/Portable/Emit/SpecializedNestedTypeReference.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.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a type nested in an instantiation of a generic type. ''' e.g. ''' A{int}.B ''' A.B{int}.C.D ''' </summary> Friend Class SpecializedNestedTypeReference Inherits NamedTypeReference Implements Cci.ISpecializedNestedTypeReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Private Function ISpecializedNestedTypeReferenceGetUnspecializedVersion(context As EmitContext) As Cci.INestedTypeReference Implements Cci.ISpecializedNestedTypeReference.GetUnspecializedVersion Debug.Assert(m_UnderlyingNamedType.OriginalDefinition Is m_UnderlyingNamedType.OriginalDefinition.OriginalDefinition) Dim result = (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.OriginalDefinition, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=True).AsNestedTypeReference Debug.Assert(result IsNot Nothing) Return result End Function Public Overrides Sub Dispatch(visitor As Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Cci.ISpecializedNestedTypeReference)) End Sub Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType Return (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference Get Return Me 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 Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a type nested in an instantiation of a generic type. ''' e.g. ''' A{int}.B ''' A.B{int}.C.D ''' </summary> Friend Class SpecializedNestedTypeReference Inherits NamedTypeReference Implements Cci.ISpecializedNestedTypeReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Private Function ISpecializedNestedTypeReferenceGetUnspecializedVersion(context As EmitContext) As Cci.INestedTypeReference Implements Cci.ISpecializedNestedTypeReference.GetUnspecializedVersion Debug.Assert(m_UnderlyingNamedType.OriginalDefinition Is m_UnderlyingNamedType.OriginalDefinition.OriginalDefinition) Dim result = (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.OriginalDefinition, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=True).AsNestedTypeReference Debug.Assert(result IsNot Nothing) Return result End Function Public Overrides Sub Dispatch(visitor As Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Cci.ISpecializedNestedTypeReference)) End Sub Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType Return (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference Get Return Me End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/IsKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class IsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IsKeywordRecommender() : base(SyntaxKind.IsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // cases: // expr | return !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class IsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IsKeywordRecommender() : base(SyntaxKind.IsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // cases: // expr | return !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/VisualBasic/Portable/CodeGeneration/FieldGenerator.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 Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module FieldGenerator Private Function LastField(Of TDeclaration As SyntaxNode)( members As SyntaxList(Of TDeclaration), fieldDeclaration As FieldDeclarationSyntax) As TDeclaration Dim lastConst = members.OfType(Of FieldDeclarationSyntax). Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() ' Place a const after the last existing const. If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return DirectCast(DirectCast(lastConst, Object), TDeclaration) End If Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)). LastOrDefault() Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() Dim result = If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword), If(lastReadOnly, If(lastNormal, lastConst)), If(lastNormal, If(lastReadOnly, lastConst))) Return DirectCast(DirectCast(result, Object), TDeclaration) End Function Friend Function AddFieldTo(destination As CompilationUnitSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As CompilationUnitSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) Return destination.WithMembers(members) End Function Friend Function AddFieldTo(destination As TypeBlockSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) ' Find the best place to put the field. It should go after the last field if we already ' have fields, or at the beginning of the file if we don't. Return FixTerminators(destination.WithMembers(members)) End Function Public Function GenerateFieldDeclaration(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As FieldDeclarationSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ModifiedIdentifierSyntax)(field, options) If reusableSyntax IsNot Nothing Then Dim variableDeclarator = TryCast(reusableSyntax.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing Then Dim names = (New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)).Add(reusableSyntax) Dim newVariableDeclarator = variableDeclarator.WithNames(names) Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax) If fieldDecl IsNot Nothing Then Return fieldDecl.WithDeclarators((New SeparatedSyntaxList(Of VariableDeclaratorSyntax)).Add(newVariableDeclarator)) End If End If End If Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax) Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field)) Dim fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options), GenerateModifiers(field, destination, options), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier), SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()), initializer))) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options)) End Function Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax If field.HasConstantValue Then Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType) Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference)) End If Return Nothing End Function Private Function GenerateModifiers(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private) If field.IsConst Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) Else If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If field.IsReadOnly Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If CodeGenerationFieldInfo.GetIsWithEvents(field) Then tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If tokens.Count = 0 Then tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Using 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module FieldGenerator Private Function LastField(Of TDeclaration As SyntaxNode)( members As SyntaxList(Of TDeclaration), fieldDeclaration As FieldDeclarationSyntax) As TDeclaration Dim lastConst = members.OfType(Of FieldDeclarationSyntax). Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() ' Place a const after the last existing const. If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return DirectCast(DirectCast(lastConst, Object), TDeclaration) End If Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)). LastOrDefault() Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() Dim result = If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword), If(lastReadOnly, If(lastNormal, lastConst)), If(lastNormal, If(lastReadOnly, lastConst))) Return DirectCast(DirectCast(result, Object), TDeclaration) End Function Friend Function AddFieldTo(destination As CompilationUnitSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As CompilationUnitSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) Return destination.WithMembers(members) End Function Friend Function AddFieldTo(destination As TypeBlockSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) ' Find the best place to put the field. It should go after the last field if we already ' have fields, or at the beginning of the file if we don't. Return FixTerminators(destination.WithMembers(members)) End Function Public Function GenerateFieldDeclaration(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As FieldDeclarationSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ModifiedIdentifierSyntax)(field, options) If reusableSyntax IsNot Nothing Then Dim variableDeclarator = TryCast(reusableSyntax.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing Then Dim names = (New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)).Add(reusableSyntax) Dim newVariableDeclarator = variableDeclarator.WithNames(names) Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax) If fieldDecl IsNot Nothing Then Return fieldDecl.WithDeclarators((New SeparatedSyntaxList(Of VariableDeclaratorSyntax)).Add(newVariableDeclarator)) End If End If End If Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax) Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field)) Dim fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options), GenerateModifiers(field, destination, options), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier), SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()), initializer))) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options)) End Function Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax If field.HasConstantValue Then Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType) Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference)) End If Return Nothing End Function Private Function GenerateModifiers(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private) If field.IsConst Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) Else If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If field.IsReadOnly Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If CodeGenerationFieldInfo.GetIsWithEvents(field) Then tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If tokens.Count = 0 Then tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Using End Function End Module End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/IteratorAndAsyncCaptureWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A walker that computes the set of local variables of an iterator/async /// method that must be hoisted to the state machine. /// </summary> /// <remarks> /// Data flow analysis is used to calculate the locals. At yield/await we mark all variables as "unassigned". /// When a read from an unassigned variables is reported we add the variable to the captured set. /// "this" parameter is captured if a reference to "this", "base" or an instance field is encountered. /// Variables used in finally also need to be captured if there is a yield in the corresponding try block. /// </remarks> internal sealed class IteratorAndAsyncCaptureWalker : DefiniteAssignmentPass { // In Release builds we hoist only variables (locals and parameters) that are captured. // This set will contain such variables after the bound tree is visited. private readonly OrderedSet<Symbol> _variablesToHoist = new OrderedSet<Symbol>(); // Contains variables that are captured but can't be hoisted since their type can't be allocated on heap. // The value is a list of all uses of each such variable. private MultiDictionary<Symbol, SyntaxNode> _lazyDisallowedCaptures; private bool _seenYieldInCurrentTry; // The initializing expressions for compiler-generated ref local temps. If the temp needs to be hoisted, then any // variables in its initializing expression will need to be hoisted too. private readonly Dictionary<LocalSymbol, BoundExpression> _boundRefLocalInitializers = new Dictionary<LocalSymbol, BoundExpression>(); private IteratorAndAsyncCaptureWalker(CSharpCompilation compilation, MethodSymbol method, BoundNode node, HashSet<Symbol> initiallyAssignedVariables) : base(compilation, method, node, EmptyStructTypeCache.CreateNeverEmpty(), trackUnassignments: true, initiallyAssignedVariables: initiallyAssignedVariables) { } // Returns deterministically ordered list of variables that ought to be hoisted. public static OrderedSet<Symbol> Analyze(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics) { var initiallyAssignedVariables = UnassignedVariablesWalker.Analyze(compilation, method, node, convertInsufficientExecutionStackExceptionToCancelledByStackGuardException: true); var walker = new IteratorAndAsyncCaptureWalker(compilation, method, node, initiallyAssignedVariables); walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true; bool badRegion = false; walker.Analyze(ref badRegion); Debug.Assert(!badRegion); if (!method.IsStatic && method.ContainingType.TypeKind == TypeKind.Struct) { // It is possible that the enclosing method only *writes* to the enclosing struct, but in that // case it should be considered captured anyway so that we have a proxy for it to write to. walker.CaptureVariable(method.ThisParameter, node.Syntax); } var lazyDisallowedCaptures = walker._lazyDisallowedCaptures; var allVariables = walker.variableBySlot; if (lazyDisallowedCaptures != null) { foreach (var kvp in lazyDisallowedCaptures) { var variable = kvp.Key; var type = (variable.Kind == SymbolKind.Local) ? ((LocalSymbol)variable).Type : ((ParameterSymbol)variable).Type; if (variable is SynthesizedLocal local && local.SynthesizedKind == SynthesizedLocalKind.Spill) { Debug.Assert(local.TypeWithAnnotations.IsRestrictedType()); diagnostics.Add(ErrorCode.ERR_ByRefTypeAndAwait, local.Locations[0], local.TypeWithAnnotations); } else { foreach (CSharpSyntaxNode syntax in kvp.Value) { // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } } } var variablesToHoist = new OrderedSet<Symbol>(); if (compilation.Options.OptimizationLevel != OptimizationLevel.Release) { // In debug build we hoist long-lived locals and parameters foreach (var v in allVariables) { var symbol = v.Symbol; if ((object)symbol != null && HoistInDebugBuild(symbol)) { variablesToHoist.Add(symbol); } } } // Hoist anything determined to be live across an await or yield variablesToHoist.AddRange(walker._variablesToHoist); walker.Free(); return variablesToHoist; } private static bool HoistInDebugBuild(Symbol symbol) { return (symbol) switch { ParameterSymbol parameter => // in Debug build hoist all parameters that can be hoisted: !parameter.Type.IsRestrictedType(), LocalSymbol { IsConst: false, IsPinned: false, IsRef: false } local => // hoist all user-defined locals and long-lived temps that can be hoisted: local.SynthesizedKind.MustSurviveStateMachineSuspension() && !local.Type.IsRestrictedType(), _ => false }; } private void MarkLocalsUnassigned() { for (int i = 0; i < variableBySlot.Count; i++) { var symbol = variableBySlot[i].Symbol; if ((object)symbol != null) { switch (symbol.Kind) { case SymbolKind.Local: if (!((LocalSymbol)symbol).IsConst) { SetSlotState(i, false); } break; case SymbolKind.Parameter: SetSlotState(i, false); break; case SymbolKind.Field: if (!((FieldSymbol)symbol).IsConst) { SetSlotState(i, false); } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } } } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { base.VisitAwaitExpression(node); MarkLocalsUnassigned(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { base.VisitYieldReturnStatement(node); MarkLocalsUnassigned(); _seenYieldInCurrentTry = true; return null; } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { _variablesToHoist.Clear(); _lazyDisallowedCaptures?.Clear(); return base.Scan(ref badRegion); } private void CaptureVariable(Symbol variable, SyntaxNode syntax) { var type = (variable.Kind == SymbolKind.Local) ? ((LocalSymbol)variable).Type : ((ParameterSymbol)variable).Type; if (type.IsRestrictedType()) { (_lazyDisallowedCaptures ??= new MultiDictionary<Symbol, SyntaxNode>()).Add(variable, syntax); } else { if (_variablesToHoist.Add(variable) && variable is LocalSymbol local && _boundRefLocalInitializers.TryGetValue(local, out var variableInitializer)) CaptureRefInitializer(variableInitializer, syntax); } } private void CaptureRefInitializer(BoundExpression variableInitializer, SyntaxNode syntax) { switch (variableInitializer) { case BoundLocal { LocalSymbol: var symbol }: CaptureVariable(symbol, syntax); break; case BoundParameter { ParameterSymbol: var symbol }: CaptureVariable(symbol, syntax); break; case BoundFieldAccess { FieldSymbol: { IsStatic: false, ContainingType: { IsValueType: true } }, ReceiverOpt: BoundExpression receiver }: CaptureRefInitializer(receiver, syntax); break; } } protected override void EnterParameter(ParameterSymbol parameter) { // Async and iterators should never have ref parameters aside from `this` Debug.Assert(parameter.IsThis || parameter.RefKind == RefKind.None); // parameters are NOT initially assigned here - if that is a problem, then // the parameters must be captured. GetOrCreateSlot(parameter); } protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) { switch (symbol.Kind) { case SymbolKind.Field: symbol = GetNonMemberSymbol(slot); goto case SymbolKind.Local; case SymbolKind.Local: case SymbolKind.Parameter: CaptureVariable(symbol, node); break; } } protected override void VisitLvalueParameter(BoundParameter node) { TryHoistTopLevelParameter(node); base.VisitLvalueParameter(node); } public override BoundNode VisitParameter(BoundParameter node) { TryHoistTopLevelParameter(node); return base.VisitParameter(node); } private void TryHoistTopLevelParameter(BoundParameter node) { if (node.ParameterSymbol.ContainingSymbol == topLevelMethod) { CaptureVariable(node.ParameterSymbol, node.Syntax); } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { if (node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.ThisReference) { var thisSymbol = topLevelMethod.ThisParameter; CaptureVariable(thisSymbol, node.Syntax); } return base.VisitFieldAccess(node); } public override BoundNode VisitThisReference(BoundThisReference node) { CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitTryStatement(BoundTryStatement node) { var origSeenYieldInCurrentTry = _seenYieldInCurrentTry; _seenYieldInCurrentTry = false; base.VisitTryStatement(node); _seenYieldInCurrentTry |= origSeenYieldInCurrentTry; return null; } protected override void VisitFinallyBlock(BoundStatement finallyBlock, ref LocalState unsetInFinally) { if (_seenYieldInCurrentTry) { // Locals cannot be used to communicate between the finally block and the rest of the method. // So we just capture any outside variables that are used inside. new OutsideVariablesUsedInside(this, this.topLevelMethod, this).Visit(finallyBlock); } base.VisitFinallyBlock(finallyBlock, ref unsetInFinally); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { base.VisitAssignmentOperator(node); // for compiler-generated ref local temp, save the initializer. if (node is { IsRef: true, Left: BoundLocal { LocalSymbol: LocalSymbol { IsCompilerGenerated: true } local } }) _boundRefLocalInitializers[local] = node.Right; return null; } private sealed class OutsideVariablesUsedInside : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly HashSet<Symbol> _localsInScope; private readonly IteratorAndAsyncCaptureWalker _analyzer; private readonly MethodSymbol _topLevelMethod; private readonly IteratorAndAsyncCaptureWalker _parent; public OutsideVariablesUsedInside(IteratorAndAsyncCaptureWalker analyzer, MethodSymbol topLevelMethod, IteratorAndAsyncCaptureWalker parent) : base(parent._recursionDepth) { _analyzer = analyzer; _topLevelMethod = topLevelMethod; _localsInScope = new HashSet<Symbol>(); _parent = parent; } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return _parent.ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException(); } public override BoundNode VisitBlock(BoundBlock node) { AddVariables(node.Locals); return base.VisitBlock(node); } private void AddVariables(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { AddVariable(local); } } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { AddVariables(node.Locals); return base.VisitCatchBlock(node); } private void AddVariable(Symbol local) { if ((object)local != null) _localsInScope.Add(local); } public override BoundNode VisitSequence(BoundSequence node) { AddVariables(node.Locals); return base.VisitSequence(node); } public override BoundNode VisitThisReference(BoundThisReference node) { Capture(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { Capture(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { Capture(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { Capture(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } private void Capture(Symbol s, SyntaxNode syntax) { if ((object)s != null && !_localsInScope.Contains(s)) { _analyzer.CaptureVariable(s, syntax); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A walker that computes the set of local variables of an iterator/async /// method that must be hoisted to the state machine. /// </summary> /// <remarks> /// Data flow analysis is used to calculate the locals. At yield/await we mark all variables as "unassigned". /// When a read from an unassigned variables is reported we add the variable to the captured set. /// "this" parameter is captured if a reference to "this", "base" or an instance field is encountered. /// Variables used in finally also need to be captured if there is a yield in the corresponding try block. /// </remarks> internal sealed class IteratorAndAsyncCaptureWalker : DefiniteAssignmentPass { // In Release builds we hoist only variables (locals and parameters) that are captured. // This set will contain such variables after the bound tree is visited. private readonly OrderedSet<Symbol> _variablesToHoist = new OrderedSet<Symbol>(); // Contains variables that are captured but can't be hoisted since their type can't be allocated on heap. // The value is a list of all uses of each such variable. private MultiDictionary<Symbol, SyntaxNode> _lazyDisallowedCaptures; private bool _seenYieldInCurrentTry; // The initializing expressions for compiler-generated ref local temps. If the temp needs to be hoisted, then any // variables in its initializing expression will need to be hoisted too. private readonly Dictionary<LocalSymbol, BoundExpression> _boundRefLocalInitializers = new Dictionary<LocalSymbol, BoundExpression>(); private IteratorAndAsyncCaptureWalker(CSharpCompilation compilation, MethodSymbol method, BoundNode node, HashSet<Symbol> initiallyAssignedVariables) : base(compilation, method, node, EmptyStructTypeCache.CreateNeverEmpty(), trackUnassignments: true, initiallyAssignedVariables: initiallyAssignedVariables) { } // Returns deterministically ordered list of variables that ought to be hoisted. public static OrderedSet<Symbol> Analyze(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics) { var initiallyAssignedVariables = UnassignedVariablesWalker.Analyze(compilation, method, node, convertInsufficientExecutionStackExceptionToCancelledByStackGuardException: true); var walker = new IteratorAndAsyncCaptureWalker(compilation, method, node, initiallyAssignedVariables); walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true; bool badRegion = false; walker.Analyze(ref badRegion); Debug.Assert(!badRegion); if (!method.IsStatic && method.ContainingType.TypeKind == TypeKind.Struct) { // It is possible that the enclosing method only *writes* to the enclosing struct, but in that // case it should be considered captured anyway so that we have a proxy for it to write to. walker.CaptureVariable(method.ThisParameter, node.Syntax); } var lazyDisallowedCaptures = walker._lazyDisallowedCaptures; var allVariables = walker.variableBySlot; if (lazyDisallowedCaptures != null) { foreach (var kvp in lazyDisallowedCaptures) { var variable = kvp.Key; var type = (variable.Kind == SymbolKind.Local) ? ((LocalSymbol)variable).Type : ((ParameterSymbol)variable).Type; if (variable is SynthesizedLocal local && local.SynthesizedKind == SynthesizedLocalKind.Spill) { Debug.Assert(local.TypeWithAnnotations.IsRestrictedType()); diagnostics.Add(ErrorCode.ERR_ByRefTypeAndAwait, local.Locations[0], local.TypeWithAnnotations); } else { foreach (CSharpSyntaxNode syntax in kvp.Value) { // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } } } var variablesToHoist = new OrderedSet<Symbol>(); if (compilation.Options.OptimizationLevel != OptimizationLevel.Release) { // In debug build we hoist long-lived locals and parameters foreach (var v in allVariables) { var symbol = v.Symbol; if ((object)symbol != null && HoistInDebugBuild(symbol)) { variablesToHoist.Add(symbol); } } } // Hoist anything determined to be live across an await or yield variablesToHoist.AddRange(walker._variablesToHoist); walker.Free(); return variablesToHoist; } private static bool HoistInDebugBuild(Symbol symbol) { return (symbol) switch { ParameterSymbol parameter => // in Debug build hoist all parameters that can be hoisted: !parameter.Type.IsRestrictedType(), LocalSymbol { IsConst: false, IsPinned: false, IsRef: false } local => // hoist all user-defined locals and long-lived temps that can be hoisted: local.SynthesizedKind.MustSurviveStateMachineSuspension() && !local.Type.IsRestrictedType(), _ => false }; } private void MarkLocalsUnassigned() { for (int i = 0; i < variableBySlot.Count; i++) { var symbol = variableBySlot[i].Symbol; if ((object)symbol != null) { switch (symbol.Kind) { case SymbolKind.Local: if (!((LocalSymbol)symbol).IsConst) { SetSlotState(i, false); } break; case SymbolKind.Parameter: SetSlotState(i, false); break; case SymbolKind.Field: if (!((FieldSymbol)symbol).IsConst) { SetSlotState(i, false); } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } } } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { base.VisitAwaitExpression(node); MarkLocalsUnassigned(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { base.VisitYieldReturnStatement(node); MarkLocalsUnassigned(); _seenYieldInCurrentTry = true; return null; } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { _variablesToHoist.Clear(); _lazyDisallowedCaptures?.Clear(); return base.Scan(ref badRegion); } private void CaptureVariable(Symbol variable, SyntaxNode syntax) { var type = (variable.Kind == SymbolKind.Local) ? ((LocalSymbol)variable).Type : ((ParameterSymbol)variable).Type; if (type.IsRestrictedType()) { (_lazyDisallowedCaptures ??= new MultiDictionary<Symbol, SyntaxNode>()).Add(variable, syntax); } else { if (_variablesToHoist.Add(variable) && variable is LocalSymbol local && _boundRefLocalInitializers.TryGetValue(local, out var variableInitializer)) CaptureRefInitializer(variableInitializer, syntax); } } private void CaptureRefInitializer(BoundExpression variableInitializer, SyntaxNode syntax) { switch (variableInitializer) { case BoundLocal { LocalSymbol: var symbol }: CaptureVariable(symbol, syntax); break; case BoundParameter { ParameterSymbol: var symbol }: CaptureVariable(symbol, syntax); break; case BoundFieldAccess { FieldSymbol: { IsStatic: false, ContainingType: { IsValueType: true } }, ReceiverOpt: BoundExpression receiver }: CaptureRefInitializer(receiver, syntax); break; } } protected override void EnterParameter(ParameterSymbol parameter) { // Async and iterators should never have ref parameters aside from `this` Debug.Assert(parameter.IsThis || parameter.RefKind == RefKind.None); // parameters are NOT initially assigned here - if that is a problem, then // the parameters must be captured. GetOrCreateSlot(parameter); } protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) { switch (symbol.Kind) { case SymbolKind.Field: symbol = GetNonMemberSymbol(slot); goto case SymbolKind.Local; case SymbolKind.Local: case SymbolKind.Parameter: CaptureVariable(symbol, node); break; } } protected override void VisitLvalueParameter(BoundParameter node) { TryHoistTopLevelParameter(node); base.VisitLvalueParameter(node); } public override BoundNode VisitParameter(BoundParameter node) { TryHoistTopLevelParameter(node); return base.VisitParameter(node); } private void TryHoistTopLevelParameter(BoundParameter node) { if (node.ParameterSymbol.ContainingSymbol == topLevelMethod) { CaptureVariable(node.ParameterSymbol, node.Syntax); } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { if (node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.ThisReference) { var thisSymbol = topLevelMethod.ThisParameter; CaptureVariable(thisSymbol, node.Syntax); } return base.VisitFieldAccess(node); } public override BoundNode VisitThisReference(BoundThisReference node) { CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitTryStatement(BoundTryStatement node) { var origSeenYieldInCurrentTry = _seenYieldInCurrentTry; _seenYieldInCurrentTry = false; base.VisitTryStatement(node); _seenYieldInCurrentTry |= origSeenYieldInCurrentTry; return null; } protected override void VisitFinallyBlock(BoundStatement finallyBlock, ref LocalState unsetInFinally) { if (_seenYieldInCurrentTry) { // Locals cannot be used to communicate between the finally block and the rest of the method. // So we just capture any outside variables that are used inside. new OutsideVariablesUsedInside(this, this.topLevelMethod, this).Visit(finallyBlock); } base.VisitFinallyBlock(finallyBlock, ref unsetInFinally); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { base.VisitAssignmentOperator(node); // for compiler-generated ref local temp, save the initializer. if (node is { IsRef: true, Left: BoundLocal { LocalSymbol: LocalSymbol { IsCompilerGenerated: true } local } }) _boundRefLocalInitializers[local] = node.Right; return null; } private sealed class OutsideVariablesUsedInside : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly HashSet<Symbol> _localsInScope; private readonly IteratorAndAsyncCaptureWalker _analyzer; private readonly MethodSymbol _topLevelMethod; private readonly IteratorAndAsyncCaptureWalker _parent; public OutsideVariablesUsedInside(IteratorAndAsyncCaptureWalker analyzer, MethodSymbol topLevelMethod, IteratorAndAsyncCaptureWalker parent) : base(parent._recursionDepth) { _analyzer = analyzer; _topLevelMethod = topLevelMethod; _localsInScope = new HashSet<Symbol>(); _parent = parent; } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return _parent.ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException(); } public override BoundNode VisitBlock(BoundBlock node) { AddVariables(node.Locals); return base.VisitBlock(node); } private void AddVariables(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { AddVariable(local); } } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { AddVariables(node.Locals); return base.VisitCatchBlock(node); } private void AddVariable(Symbol local) { if ((object)local != null) _localsInScope.Add(local); } public override BoundNode VisitSequence(BoundSequence node) { AddVariables(node.Locals); return base.VisitSequence(node); } public override BoundNode VisitThisReference(BoundThisReference node) { Capture(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { Capture(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { Capture(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { Capture(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } private void Capture(Symbol s, SyntaxNode syntax) { if ((object)s != null && !_localsInScope.Contains(s)) { _analyzer.CaptureVariable(s, syntax); } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/VisualBasic/Portable/SignatureHelp/ConditionalExpressionSignatureHelpProvider.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.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Friend MustInherit Class ConditionalExpressionSignatureHelpProvider(Of T As SyntaxNode) Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of T) Protected MustOverride ReadOnly Property Kind As SyntaxKind Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As T, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New BinaryConditionalExpressionDocumentation(), New TernaryConditionalExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) AndAlso token.Parent.Kind = Kind End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As T, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso (token.Kind <> SyntaxKind.CloseParenToken OrElse token.Parent.Kind <> Kind) End Function End Class <ExportSignatureHelpProvider("BinaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class BinaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of BinaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.BinaryConditionalExpression End Get End Property End Class <ExportSignatureHelpProvider("TernaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class TernaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of TernaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.TernaryConditionalExpression 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Friend MustInherit Class ConditionalExpressionSignatureHelpProvider(Of T As SyntaxNode) Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of T) Protected MustOverride ReadOnly Property Kind As SyntaxKind Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As T, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New BinaryConditionalExpressionDocumentation(), New TernaryConditionalExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) AndAlso token.Parent.Kind = Kind End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As T, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso (token.Kind <> SyntaxKind.CloseParenToken OrElse token.Parent.Kind <> Kind) End Function End Class <ExportSignatureHelpProvider("BinaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class BinaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of BinaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.BinaryConditionalExpression End Get End Property End Class <ExportSignatureHelpProvider("TernaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class TernaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of TernaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.TernaryConditionalExpression End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.UseExplicitOrImplicitType { [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] public class UseImplicitTypeRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseImplicitTypeCodeRefactoringProvider(); [Fact] public async Task TestIntLocalDeclaration() { var code = @" class C { static void Main() { int[||] i = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestSelection1() { var code = @" class C { static void Main() { [|int i = 0;|] } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestSelection2() { var code = @" class C { static void Main() { [|int|] i = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectionNotType() { var code = @" class C { static void Main() { int [|i|] = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestForeachInsideLocalDeclaration() { var code = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } }"; var expected = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInIntPattern() { var code = @" class C { static void Main() { _ = 0 is int[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_Multiple() { var code = @" class C { static void Main() { int[||] i = 0, j = j; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_NoInitializer() { var code = @" class C { static void Main() { int[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForLoop() { var code = @" class C { static void Main() { for (int[||] i = 0;;) { } } }"; var expected = @" class C { static void Main() { for (var i = 0;;) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInDispose() { var code = @" class C : System.IDisposable { static void Main() { using (C[||] c = new C()) { } } }"; var expected = @" class C : System.IDisposable { static void Main() { using (var c = new C()) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntForeachLoop() { var code = @" class C { static void Main() { foreach (int[||] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop2() { var code = @" class C { static void Main() { foreach ([|int|] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop3() { var code = @" class C { static void Main() { foreach (int [|i|] in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop4() { var code = @" class C { static void Main() { foreach ([|object|] i in new[] { new object() }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { new object() }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction() { var code = @" class C { static void Main() { (int[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (var i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction2() { var code = @" class C { static void Main() { (int[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (var i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { var code = @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (string arg in [|args|]) { } } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task NoSuggestionWithinAnExpression() { var code = @"using System; using System; class C { static void Main(string[] args) { int a = 40 [||]+ 2; } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal1() { var code = @" class C { static void Main() { string str = """"; [||]ref string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal2() { var code = @" class C { static void Main() { string str = """"; ref [||]string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal3() { var code = @" class C { static void Main() { string str = """"; ref string [||]rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal1() { var code = @" class C { static void Main() { string str = """"; ref readonly [||]string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal2() { var code = @" class C { static void Main() { string str = """"; ref readonly string[||] rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { // Enabled because the diagnostic is disabled await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithNone()); // Enabled because the diagnostic is checking for the other direction await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithNone()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithSilent()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithInfo()); // Disabled because the diagnostic will report it instead await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); // Currently this refactoring is still enabled in cases where it would cause a warning or error await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithWarning()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithError()); } private async Task TestMissingInRegularAndScriptAsync(string initialMarkup) { await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.UseExplicitOrImplicitType { [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] public class UseImplicitTypeRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseImplicitTypeCodeRefactoringProvider(); [Fact] public async Task TestIntLocalDeclaration() { var code = @" class C { static void Main() { int[||] i = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestSelection1() { var code = @" class C { static void Main() { [|int i = 0;|] } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestSelection2() { var code = @" class C { static void Main() { [|int|] i = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectionNotType() { var code = @" class C { static void Main() { int [|i|] = 0; } }"; var expected = @" class C { static void Main() { var i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestForeachInsideLocalDeclaration() { var code = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } }"; var expected = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInIntPattern() { var code = @" class C { static void Main() { _ = 0 is int[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_Multiple() { var code = @" class C { static void Main() { int[||] i = 0, j = j; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_NoInitializer() { var code = @" class C { static void Main() { int[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForLoop() { var code = @" class C { static void Main() { for (int[||] i = 0;;) { } } }"; var expected = @" class C { static void Main() { for (var i = 0;;) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInDispose() { var code = @" class C : System.IDisposable { static void Main() { using (C[||] c = new C()) { } } }"; var expected = @" class C : System.IDisposable { static void Main() { using (var c = new C()) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntForeachLoop() { var code = @" class C { static void Main() { foreach (int[||] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop2() { var code = @" class C { static void Main() { foreach ([|int|] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop3() { var code = @" class C { static void Main() { foreach (int [|i|] in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestIntForeachLoop4() { var code = @" class C { static void Main() { foreach ([|object|] i in new[] { new object() }) { } } }"; var expected = @" class C { static void Main() { foreach (var i in new[] { new object() }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction() { var code = @" class C { static void Main() { (int[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (var i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction2() { var code = @" class C { static void Main() { (int[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (var i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { var code = @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (string arg in [|args|]) { } } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task NoSuggestionWithinAnExpression() { var code = @"using System; using System; class C { static void Main(string[] args) { int a = 40 [||]+ 2; } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal1() { var code = @" class C { static void Main() { string str = """"; [||]ref string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal2() { var code = @" class C { static void Main() { string str = """"; ref [||]string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal3() { var code = @" class C { static void Main() { string str = """"; ref string [||]rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal1() { var code = @" class C { static void Main() { string str = """"; ref readonly [||]string rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal2() { var code = @" class C { static void Main() { string str = """"; ref readonly string[||] rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly var rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { // Enabled because the diagnostic is disabled await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithNone()); // Enabled because the diagnostic is checking for the other direction await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithNone()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithSilent()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithInfo()); // Disabled because the diagnostic will report it instead await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); // Currently this refactoring is still enabled in cases where it would cause a warning or error await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithWarning()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithError()); } private async Task TestMissingInRegularAndScriptAsync(string initialMarkup) { await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/CodeGen/ILOpCodeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { internal static partial class ILOpCodeExtensions { public static int Size(this ILOpCode opcode) { int code = (int)opcode; if (code <= 0xff) { Debug.Assert(code < 0xf0); return 1; } else { Debug.Assert((code & 0xff00) == 0xfe00); return 2; } } public static ILOpCode GetLeaveOpcode(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Br: return ILOpCode.Leave; case ILOpCode.Br_s: return ILOpCode.Leave_s; } throw ExceptionUtilities.UnexpectedValue(opcode); } public static bool HasVariableStackBehavior(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Call: case ILOpCode.Calli: case ILOpCode.Callvirt: case ILOpCode.Newobj: case ILOpCode.Ret: return true; } return false; } /// <summary> /// These opcodes represent control transfer. /// They should not appear inside basic blocks. /// </summary> public static bool IsControlTransfer(this ILOpCode opcode) { if (opcode.IsBranch()) { return true; } switch (opcode) { case ILOpCode.Ret: case ILOpCode.Throw: case ILOpCode.Rethrow: case ILOpCode.Endfilter: case ILOpCode.Endfinally: case ILOpCode.Switch: case ILOpCode.Jmp: return true; } return false; } public static bool IsConditionalBranch(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Brtrue: case ILOpCode.Brtrue_s: case ILOpCode.Brfalse: case ILOpCode.Brfalse_s: case ILOpCode.Beq: case ILOpCode.Beq_s: case ILOpCode.Bne_un: case ILOpCode.Bne_un_s: case ILOpCode.Bge: case ILOpCode.Bge_s: case ILOpCode.Bge_un: case ILOpCode.Bge_un_s: case ILOpCode.Bgt: case ILOpCode.Bgt_s: case ILOpCode.Bgt_un: case ILOpCode.Bgt_un_s: case ILOpCode.Ble: case ILOpCode.Ble_s: case ILOpCode.Ble_un: case ILOpCode.Ble_un_s: case ILOpCode.Blt: case ILOpCode.Blt_s: case ILOpCode.Blt_un: case ILOpCode.Blt_un_s: return true; // these are not conditional //case ILOpCode.Br: //case ILOpCode.Br_s: //case ILOpCode.Leave: //case ILOpCode.Leave_s: // this is treated specially. It will not use regular single label //case ILOpCode.Switch } return false; } public static bool IsRelationalBranch(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Beq: case ILOpCode.Beq_s: case ILOpCode.Bne_un: case ILOpCode.Bne_un_s: case ILOpCode.Bge: case ILOpCode.Bge_s: case ILOpCode.Bge_un: case ILOpCode.Bge_un_s: case ILOpCode.Bgt: case ILOpCode.Bgt_s: case ILOpCode.Bgt_un: case ILOpCode.Bgt_un_s: case ILOpCode.Ble: case ILOpCode.Ble_s: case ILOpCode.Ble_un: case ILOpCode.Ble_un_s: case ILOpCode.Blt: case ILOpCode.Blt_s: case ILOpCode.Blt_un: case ILOpCode.Blt_un_s: return true; } return false; } /// <summary> /// Opcodes that represents a branch to a label. /// </summary> public static bool CanFallThrough(this ILOpCode opcode) { //12.4.2.8.1 Most instructions can allow control to fall through after their execution—only unconditional branches, //ret, jmp, leave(.s), endfinally, endfault, endfilter, throw, and rethrow do not. switch (opcode) { case ILOpCode.Br: case ILOpCode.Br_s: case ILOpCode.Ret: case ILOpCode.Jmp: case ILOpCode.Throw: //NOTE: from the codegen view endfilter is a logical "brfalse <continueHandlerSearch>" // endfilter must be used once at the end of the filter and must be lexically followed by the handler // to which the control returns if filter result was 1. //case ILOpCode.Endfilter: case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: case ILOpCode.Rethrow: return false; } return true; } public static int NetStackBehavior(this ILOpCode opcode) { Debug.Assert(!opcode.HasVariableStackBehavior()); return opcode.StackPushCount() - opcode.StackPopCount(); } public static int StackPopCount(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Nop: case ILOpCode.Break: case ILOpCode.Ldarg_0: case ILOpCode.Ldarg_1: case ILOpCode.Ldarg_2: case ILOpCode.Ldarg_3: case ILOpCode.Ldloc_0: case ILOpCode.Ldloc_1: case ILOpCode.Ldloc_2: case ILOpCode.Ldloc_3: return 0; case ILOpCode.Stloc_0: case ILOpCode.Stloc_1: case ILOpCode.Stloc_2: case ILOpCode.Stloc_3: return 1; case ILOpCode.Ldarg_s: case ILOpCode.Ldarga_s: return 0; case ILOpCode.Starg_s: return 1; case ILOpCode.Ldloc_s: case ILOpCode.Ldloca_s: return 0; case ILOpCode.Stloc_s: return 1; case ILOpCode.Ldnull: case ILOpCode.Ldc_i4_m1: case ILOpCode.Ldc_i4_0: case ILOpCode.Ldc_i4_1: case ILOpCode.Ldc_i4_2: case ILOpCode.Ldc_i4_3: case ILOpCode.Ldc_i4_4: case ILOpCode.Ldc_i4_5: case ILOpCode.Ldc_i4_6: case ILOpCode.Ldc_i4_7: case ILOpCode.Ldc_i4_8: case ILOpCode.Ldc_i4_s: case ILOpCode.Ldc_i4: case ILOpCode.Ldc_i8: case ILOpCode.Ldc_r4: case ILOpCode.Ldc_r8: return 0; case ILOpCode.Dup: case ILOpCode.Pop: return 1; case ILOpCode.Jmp: return 0; case ILOpCode.Call: case ILOpCode.Calli: case ILOpCode.Ret: return -1; // Variable case ILOpCode.Br_s: return 0; case ILOpCode.Brfalse_s: case ILOpCode.Brtrue_s: return 1; case ILOpCode.Beq_s: case ILOpCode.Bge_s: case ILOpCode.Bgt_s: case ILOpCode.Ble_s: case ILOpCode.Blt_s: case ILOpCode.Bne_un_s: case ILOpCode.Bge_un_s: case ILOpCode.Bgt_un_s: case ILOpCode.Ble_un_s: case ILOpCode.Blt_un_s: return 2; case ILOpCode.Br: return 0; case ILOpCode.Brfalse: case ILOpCode.Brtrue: return 1; case ILOpCode.Beq: case ILOpCode.Bge: case ILOpCode.Bgt: case ILOpCode.Ble: case ILOpCode.Blt: case ILOpCode.Bne_un: case ILOpCode.Bge_un: case ILOpCode.Bgt_un: case ILOpCode.Ble_un: case ILOpCode.Blt_un: return 2; case ILOpCode.Switch: case ILOpCode.Ldind_i1: case ILOpCode.Ldind_u1: case ILOpCode.Ldind_i2: case ILOpCode.Ldind_u2: case ILOpCode.Ldind_i4: case ILOpCode.Ldind_u4: case ILOpCode.Ldind_i8: case ILOpCode.Ldind_i: case ILOpCode.Ldind_r4: case ILOpCode.Ldind_r8: case ILOpCode.Ldind_ref: return 1; case ILOpCode.Stind_ref: case ILOpCode.Stind_i1: case ILOpCode.Stind_i2: case ILOpCode.Stind_i4: case ILOpCode.Stind_i8: case ILOpCode.Stind_r4: case ILOpCode.Stind_r8: case ILOpCode.Add: case ILOpCode.Sub: case ILOpCode.Mul: case ILOpCode.Div: case ILOpCode.Div_un: case ILOpCode.Rem: case ILOpCode.Rem_un: case ILOpCode.And: case ILOpCode.Or: case ILOpCode.Xor: case ILOpCode.Shl: case ILOpCode.Shr: case ILOpCode.Shr_un: return 2; case ILOpCode.Neg: case ILOpCode.Not: case ILOpCode.Conv_i1: case ILOpCode.Conv_i2: case ILOpCode.Conv_i4: case ILOpCode.Conv_i8: case ILOpCode.Conv_r4: case ILOpCode.Conv_r8: case ILOpCode.Conv_u4: case ILOpCode.Conv_u8: return 1; case ILOpCode.Callvirt: return -1; // Variable case ILOpCode.Cpobj: return 2; case ILOpCode.Ldobj: return 1; case ILOpCode.Ldstr: return 0; case ILOpCode.Newobj: return -1; // Variable case ILOpCode.Castclass: case ILOpCode.Isinst: case ILOpCode.Conv_r_un: case ILOpCode.Unbox: case ILOpCode.Throw: case ILOpCode.Ldfld: case ILOpCode.Ldflda: return 1; case ILOpCode.Stfld: return 2; case ILOpCode.Ldsfld: case ILOpCode.Ldsflda: return 0; case ILOpCode.Stsfld: return 1; case ILOpCode.Stobj: return 2; case ILOpCode.Conv_ovf_i1_un: case ILOpCode.Conv_ovf_i2_un: case ILOpCode.Conv_ovf_i4_un: case ILOpCode.Conv_ovf_i8_un: case ILOpCode.Conv_ovf_u1_un: case ILOpCode.Conv_ovf_u2_un: case ILOpCode.Conv_ovf_u4_un: case ILOpCode.Conv_ovf_u8_un: case ILOpCode.Conv_ovf_i_un: case ILOpCode.Conv_ovf_u_un: case ILOpCode.Box: case ILOpCode.Newarr: case ILOpCode.Ldlen: return 1; case ILOpCode.Ldelema: case ILOpCode.Ldelem_i1: case ILOpCode.Ldelem_u1: case ILOpCode.Ldelem_i2: case ILOpCode.Ldelem_u2: case ILOpCode.Ldelem_i4: case ILOpCode.Ldelem_u4: case ILOpCode.Ldelem_i8: case ILOpCode.Ldelem_i: case ILOpCode.Ldelem_r4: case ILOpCode.Ldelem_r8: case ILOpCode.Ldelem_ref: return 2; case ILOpCode.Stelem_i: case ILOpCode.Stelem_i1: case ILOpCode.Stelem_i2: case ILOpCode.Stelem_i4: case ILOpCode.Stelem_i8: case ILOpCode.Stelem_r4: case ILOpCode.Stelem_r8: case ILOpCode.Stelem_ref: return 3; case ILOpCode.Ldelem: return 2; case ILOpCode.Stelem: return 3; case ILOpCode.Unbox_any: case ILOpCode.Conv_ovf_i1: case ILOpCode.Conv_ovf_u1: case ILOpCode.Conv_ovf_i2: case ILOpCode.Conv_ovf_u2: case ILOpCode.Conv_ovf_i4: case ILOpCode.Conv_ovf_u4: case ILOpCode.Conv_ovf_i8: case ILOpCode.Conv_ovf_u8: case ILOpCode.Refanyval: case ILOpCode.Ckfinite: case ILOpCode.Mkrefany: return 1; case ILOpCode.Ldtoken: return 0; case ILOpCode.Conv_u2: case ILOpCode.Conv_u1: case ILOpCode.Conv_i: case ILOpCode.Conv_ovf_i: case ILOpCode.Conv_ovf_u: return 1; case ILOpCode.Add_ovf: case ILOpCode.Add_ovf_un: case ILOpCode.Mul_ovf: case ILOpCode.Mul_ovf_un: case ILOpCode.Sub_ovf: case ILOpCode.Sub_ovf_un: return 2; case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: return 0; case ILOpCode.Stind_i: return 2; case ILOpCode.Conv_u: return 1; case ILOpCode.Arglist: return 0; case ILOpCode.Ceq: case ILOpCode.Cgt: case ILOpCode.Cgt_un: case ILOpCode.Clt: case ILOpCode.Clt_un: return 2; case ILOpCode.Ldftn: return 0; case ILOpCode.Ldvirtftn: return 1; case ILOpCode.Ldarg: case ILOpCode.Ldarga: return 0; case ILOpCode.Starg: return 1; case ILOpCode.Ldloc: case ILOpCode.Ldloca: return 0; case ILOpCode.Stloc: case ILOpCode.Localloc: case ILOpCode.Endfilter: return 1; case ILOpCode.Unaligned: case ILOpCode.Volatile: case ILOpCode.Tail: return 0; case ILOpCode.Initobj: return 1; case ILOpCode.Constrained: return 0; case ILOpCode.Cpblk: case ILOpCode.Initblk: return 3; case ILOpCode.Rethrow: case ILOpCode.Sizeof: return 0; case ILOpCode.Refanytype: return 1; case ILOpCode.Readonly: return 0; } throw ExceptionUtilities.UnexpectedValue(opcode); } public static int StackPushCount(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Nop: case ILOpCode.Break: return 0; case ILOpCode.Ldarg_0: case ILOpCode.Ldarg_1: case ILOpCode.Ldarg_2: case ILOpCode.Ldarg_3: case ILOpCode.Ldloc_0: case ILOpCode.Ldloc_1: case ILOpCode.Ldloc_2: case ILOpCode.Ldloc_3: return 1; case ILOpCode.Stloc_0: case ILOpCode.Stloc_1: case ILOpCode.Stloc_2: case ILOpCode.Stloc_3: return 0; case ILOpCode.Ldarg_s: case ILOpCode.Ldarga_s: return 1; case ILOpCode.Starg_s: return 0; case ILOpCode.Ldloc_s: case ILOpCode.Ldloca_s: return 1; case ILOpCode.Stloc_s: return 0; case ILOpCode.Ldnull: case ILOpCode.Ldc_i4_m1: case ILOpCode.Ldc_i4_0: case ILOpCode.Ldc_i4_1: case ILOpCode.Ldc_i4_2: case ILOpCode.Ldc_i4_3: case ILOpCode.Ldc_i4_4: case ILOpCode.Ldc_i4_5: case ILOpCode.Ldc_i4_6: case ILOpCode.Ldc_i4_7: case ILOpCode.Ldc_i4_8: case ILOpCode.Ldc_i4_s: case ILOpCode.Ldc_i4: case ILOpCode.Ldc_i8: case ILOpCode.Ldc_r4: case ILOpCode.Ldc_r8: return 1; case ILOpCode.Dup: return 2; case ILOpCode.Pop: case ILOpCode.Jmp: return 0; case ILOpCode.Call: case ILOpCode.Calli: return -1; // Variable case ILOpCode.Ret: case ILOpCode.Br_s: case ILOpCode.Brfalse_s: case ILOpCode.Brtrue_s: case ILOpCode.Beq_s: case ILOpCode.Bge_s: case ILOpCode.Bgt_s: case ILOpCode.Ble_s: case ILOpCode.Blt_s: case ILOpCode.Bne_un_s: case ILOpCode.Bge_un_s: case ILOpCode.Bgt_un_s: case ILOpCode.Ble_un_s: case ILOpCode.Blt_un_s: case ILOpCode.Br: case ILOpCode.Brfalse: case ILOpCode.Brtrue: case ILOpCode.Beq: case ILOpCode.Bge: case ILOpCode.Bgt: case ILOpCode.Ble: case ILOpCode.Blt: case ILOpCode.Bne_un: case ILOpCode.Bge_un: case ILOpCode.Bgt_un: case ILOpCode.Ble_un: case ILOpCode.Blt_un: case ILOpCode.Switch: return 0; case ILOpCode.Ldind_i1: case ILOpCode.Ldind_u1: case ILOpCode.Ldind_i2: case ILOpCode.Ldind_u2: case ILOpCode.Ldind_i4: case ILOpCode.Ldind_u4: case ILOpCode.Ldind_i8: case ILOpCode.Ldind_i: case ILOpCode.Ldind_r4: case ILOpCode.Ldind_r8: case ILOpCode.Ldind_ref: return 1; case ILOpCode.Stind_ref: case ILOpCode.Stind_i1: case ILOpCode.Stind_i2: case ILOpCode.Stind_i4: case ILOpCode.Stind_i8: case ILOpCode.Stind_r4: case ILOpCode.Stind_r8: return 0; case ILOpCode.Add: case ILOpCode.Sub: case ILOpCode.Mul: case ILOpCode.Div: case ILOpCode.Div_un: case ILOpCode.Rem: case ILOpCode.Rem_un: case ILOpCode.And: case ILOpCode.Or: case ILOpCode.Xor: case ILOpCode.Shl: case ILOpCode.Shr: case ILOpCode.Shr_un: case ILOpCode.Neg: case ILOpCode.Not: case ILOpCode.Conv_i1: case ILOpCode.Conv_i2: case ILOpCode.Conv_i4: case ILOpCode.Conv_i8: case ILOpCode.Conv_r4: case ILOpCode.Conv_r8: case ILOpCode.Conv_u4: case ILOpCode.Conv_u8: return 1; case ILOpCode.Callvirt: return -1; // Variable case ILOpCode.Cpobj: return 0; case ILOpCode.Ldobj: case ILOpCode.Ldstr: case ILOpCode.Newobj: case ILOpCode.Castclass: case ILOpCode.Isinst: case ILOpCode.Conv_r_un: case ILOpCode.Unbox: return 1; case ILOpCode.Throw: return 0; case ILOpCode.Ldfld: case ILOpCode.Ldflda: return 1; case ILOpCode.Stfld: return 0; case ILOpCode.Ldsfld: case ILOpCode.Ldsflda: return 1; case ILOpCode.Stsfld: case ILOpCode.Stobj: return 0; case ILOpCode.Conv_ovf_i1_un: case ILOpCode.Conv_ovf_i2_un: case ILOpCode.Conv_ovf_i4_un: case ILOpCode.Conv_ovf_i8_un: case ILOpCode.Conv_ovf_u1_un: case ILOpCode.Conv_ovf_u2_un: case ILOpCode.Conv_ovf_u4_un: case ILOpCode.Conv_ovf_u8_un: case ILOpCode.Conv_ovf_i_un: case ILOpCode.Conv_ovf_u_un: case ILOpCode.Box: case ILOpCode.Newarr: case ILOpCode.Ldlen: case ILOpCode.Ldelema: case ILOpCode.Ldelem_i1: case ILOpCode.Ldelem_u1: case ILOpCode.Ldelem_i2: case ILOpCode.Ldelem_u2: case ILOpCode.Ldelem_i4: case ILOpCode.Ldelem_u4: case ILOpCode.Ldelem_i8: case ILOpCode.Ldelem_i: case ILOpCode.Ldelem_r4: case ILOpCode.Ldelem_r8: case ILOpCode.Ldelem_ref: return 1; case ILOpCode.Stelem_i: case ILOpCode.Stelem_i1: case ILOpCode.Stelem_i2: case ILOpCode.Stelem_i4: case ILOpCode.Stelem_i8: case ILOpCode.Stelem_r4: case ILOpCode.Stelem_r8: case ILOpCode.Stelem_ref: return 0; case ILOpCode.Ldelem: return 1; case ILOpCode.Stelem: return 0; case ILOpCode.Unbox_any: case ILOpCode.Conv_ovf_i1: case ILOpCode.Conv_ovf_u1: case ILOpCode.Conv_ovf_i2: case ILOpCode.Conv_ovf_u2: case ILOpCode.Conv_ovf_i4: case ILOpCode.Conv_ovf_u4: case ILOpCode.Conv_ovf_i8: case ILOpCode.Conv_ovf_u8: case ILOpCode.Refanyval: case ILOpCode.Ckfinite: case ILOpCode.Mkrefany: case ILOpCode.Ldtoken: case ILOpCode.Conv_u2: case ILOpCode.Conv_u1: case ILOpCode.Conv_i: case ILOpCode.Conv_ovf_i: case ILOpCode.Conv_ovf_u: case ILOpCode.Add_ovf: case ILOpCode.Add_ovf_un: case ILOpCode.Mul_ovf: case ILOpCode.Mul_ovf_un: case ILOpCode.Sub_ovf: case ILOpCode.Sub_ovf_un: return 1; case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: case ILOpCode.Stind_i: return 0; case ILOpCode.Conv_u: case ILOpCode.Arglist: case ILOpCode.Ceq: case ILOpCode.Cgt: case ILOpCode.Cgt_un: case ILOpCode.Clt: case ILOpCode.Clt_un: case ILOpCode.Ldftn: case ILOpCode.Ldvirtftn: case ILOpCode.Ldarg: case ILOpCode.Ldarga: return 1; case ILOpCode.Starg: return 0; case ILOpCode.Ldloc: case ILOpCode.Ldloca: return 1; case ILOpCode.Stloc: return 0; case ILOpCode.Localloc: return 1; case ILOpCode.Endfilter: case ILOpCode.Unaligned: case ILOpCode.Volatile: case ILOpCode.Tail: case ILOpCode.Initobj: case ILOpCode.Constrained: case ILOpCode.Cpblk: case ILOpCode.Initblk: case ILOpCode.Rethrow: return 0; case ILOpCode.Sizeof: case ILOpCode.Refanytype: return 1; case ILOpCode.Readonly: return 0; } throw ExceptionUtilities.UnexpectedValue(opcode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { internal static partial class ILOpCodeExtensions { public static int Size(this ILOpCode opcode) { int code = (int)opcode; if (code <= 0xff) { Debug.Assert(code < 0xf0); return 1; } else { Debug.Assert((code & 0xff00) == 0xfe00); return 2; } } public static ILOpCode GetLeaveOpcode(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Br: return ILOpCode.Leave; case ILOpCode.Br_s: return ILOpCode.Leave_s; } throw ExceptionUtilities.UnexpectedValue(opcode); } public static bool HasVariableStackBehavior(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Call: case ILOpCode.Calli: case ILOpCode.Callvirt: case ILOpCode.Newobj: case ILOpCode.Ret: return true; } return false; } /// <summary> /// These opcodes represent control transfer. /// They should not appear inside basic blocks. /// </summary> public static bool IsControlTransfer(this ILOpCode opcode) { if (opcode.IsBranch()) { return true; } switch (opcode) { case ILOpCode.Ret: case ILOpCode.Throw: case ILOpCode.Rethrow: case ILOpCode.Endfilter: case ILOpCode.Endfinally: case ILOpCode.Switch: case ILOpCode.Jmp: return true; } return false; } public static bool IsConditionalBranch(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Brtrue: case ILOpCode.Brtrue_s: case ILOpCode.Brfalse: case ILOpCode.Brfalse_s: case ILOpCode.Beq: case ILOpCode.Beq_s: case ILOpCode.Bne_un: case ILOpCode.Bne_un_s: case ILOpCode.Bge: case ILOpCode.Bge_s: case ILOpCode.Bge_un: case ILOpCode.Bge_un_s: case ILOpCode.Bgt: case ILOpCode.Bgt_s: case ILOpCode.Bgt_un: case ILOpCode.Bgt_un_s: case ILOpCode.Ble: case ILOpCode.Ble_s: case ILOpCode.Ble_un: case ILOpCode.Ble_un_s: case ILOpCode.Blt: case ILOpCode.Blt_s: case ILOpCode.Blt_un: case ILOpCode.Blt_un_s: return true; // these are not conditional //case ILOpCode.Br: //case ILOpCode.Br_s: //case ILOpCode.Leave: //case ILOpCode.Leave_s: // this is treated specially. It will not use regular single label //case ILOpCode.Switch } return false; } public static bool IsRelationalBranch(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Beq: case ILOpCode.Beq_s: case ILOpCode.Bne_un: case ILOpCode.Bne_un_s: case ILOpCode.Bge: case ILOpCode.Bge_s: case ILOpCode.Bge_un: case ILOpCode.Bge_un_s: case ILOpCode.Bgt: case ILOpCode.Bgt_s: case ILOpCode.Bgt_un: case ILOpCode.Bgt_un_s: case ILOpCode.Ble: case ILOpCode.Ble_s: case ILOpCode.Ble_un: case ILOpCode.Ble_un_s: case ILOpCode.Blt: case ILOpCode.Blt_s: case ILOpCode.Blt_un: case ILOpCode.Blt_un_s: return true; } return false; } /// <summary> /// Opcodes that represents a branch to a label. /// </summary> public static bool CanFallThrough(this ILOpCode opcode) { //12.4.2.8.1 Most instructions can allow control to fall through after their execution—only unconditional branches, //ret, jmp, leave(.s), endfinally, endfault, endfilter, throw, and rethrow do not. switch (opcode) { case ILOpCode.Br: case ILOpCode.Br_s: case ILOpCode.Ret: case ILOpCode.Jmp: case ILOpCode.Throw: //NOTE: from the codegen view endfilter is a logical "brfalse <continueHandlerSearch>" // endfilter must be used once at the end of the filter and must be lexically followed by the handler // to which the control returns if filter result was 1. //case ILOpCode.Endfilter: case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: case ILOpCode.Rethrow: return false; } return true; } public static int NetStackBehavior(this ILOpCode opcode) { Debug.Assert(!opcode.HasVariableStackBehavior()); return opcode.StackPushCount() - opcode.StackPopCount(); } public static int StackPopCount(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Nop: case ILOpCode.Break: case ILOpCode.Ldarg_0: case ILOpCode.Ldarg_1: case ILOpCode.Ldarg_2: case ILOpCode.Ldarg_3: case ILOpCode.Ldloc_0: case ILOpCode.Ldloc_1: case ILOpCode.Ldloc_2: case ILOpCode.Ldloc_3: return 0; case ILOpCode.Stloc_0: case ILOpCode.Stloc_1: case ILOpCode.Stloc_2: case ILOpCode.Stloc_3: return 1; case ILOpCode.Ldarg_s: case ILOpCode.Ldarga_s: return 0; case ILOpCode.Starg_s: return 1; case ILOpCode.Ldloc_s: case ILOpCode.Ldloca_s: return 0; case ILOpCode.Stloc_s: return 1; case ILOpCode.Ldnull: case ILOpCode.Ldc_i4_m1: case ILOpCode.Ldc_i4_0: case ILOpCode.Ldc_i4_1: case ILOpCode.Ldc_i4_2: case ILOpCode.Ldc_i4_3: case ILOpCode.Ldc_i4_4: case ILOpCode.Ldc_i4_5: case ILOpCode.Ldc_i4_6: case ILOpCode.Ldc_i4_7: case ILOpCode.Ldc_i4_8: case ILOpCode.Ldc_i4_s: case ILOpCode.Ldc_i4: case ILOpCode.Ldc_i8: case ILOpCode.Ldc_r4: case ILOpCode.Ldc_r8: return 0; case ILOpCode.Dup: case ILOpCode.Pop: return 1; case ILOpCode.Jmp: return 0; case ILOpCode.Call: case ILOpCode.Calli: case ILOpCode.Ret: return -1; // Variable case ILOpCode.Br_s: return 0; case ILOpCode.Brfalse_s: case ILOpCode.Brtrue_s: return 1; case ILOpCode.Beq_s: case ILOpCode.Bge_s: case ILOpCode.Bgt_s: case ILOpCode.Ble_s: case ILOpCode.Blt_s: case ILOpCode.Bne_un_s: case ILOpCode.Bge_un_s: case ILOpCode.Bgt_un_s: case ILOpCode.Ble_un_s: case ILOpCode.Blt_un_s: return 2; case ILOpCode.Br: return 0; case ILOpCode.Brfalse: case ILOpCode.Brtrue: return 1; case ILOpCode.Beq: case ILOpCode.Bge: case ILOpCode.Bgt: case ILOpCode.Ble: case ILOpCode.Blt: case ILOpCode.Bne_un: case ILOpCode.Bge_un: case ILOpCode.Bgt_un: case ILOpCode.Ble_un: case ILOpCode.Blt_un: return 2; case ILOpCode.Switch: case ILOpCode.Ldind_i1: case ILOpCode.Ldind_u1: case ILOpCode.Ldind_i2: case ILOpCode.Ldind_u2: case ILOpCode.Ldind_i4: case ILOpCode.Ldind_u4: case ILOpCode.Ldind_i8: case ILOpCode.Ldind_i: case ILOpCode.Ldind_r4: case ILOpCode.Ldind_r8: case ILOpCode.Ldind_ref: return 1; case ILOpCode.Stind_ref: case ILOpCode.Stind_i1: case ILOpCode.Stind_i2: case ILOpCode.Stind_i4: case ILOpCode.Stind_i8: case ILOpCode.Stind_r4: case ILOpCode.Stind_r8: case ILOpCode.Add: case ILOpCode.Sub: case ILOpCode.Mul: case ILOpCode.Div: case ILOpCode.Div_un: case ILOpCode.Rem: case ILOpCode.Rem_un: case ILOpCode.And: case ILOpCode.Or: case ILOpCode.Xor: case ILOpCode.Shl: case ILOpCode.Shr: case ILOpCode.Shr_un: return 2; case ILOpCode.Neg: case ILOpCode.Not: case ILOpCode.Conv_i1: case ILOpCode.Conv_i2: case ILOpCode.Conv_i4: case ILOpCode.Conv_i8: case ILOpCode.Conv_r4: case ILOpCode.Conv_r8: case ILOpCode.Conv_u4: case ILOpCode.Conv_u8: return 1; case ILOpCode.Callvirt: return -1; // Variable case ILOpCode.Cpobj: return 2; case ILOpCode.Ldobj: return 1; case ILOpCode.Ldstr: return 0; case ILOpCode.Newobj: return -1; // Variable case ILOpCode.Castclass: case ILOpCode.Isinst: case ILOpCode.Conv_r_un: case ILOpCode.Unbox: case ILOpCode.Throw: case ILOpCode.Ldfld: case ILOpCode.Ldflda: return 1; case ILOpCode.Stfld: return 2; case ILOpCode.Ldsfld: case ILOpCode.Ldsflda: return 0; case ILOpCode.Stsfld: return 1; case ILOpCode.Stobj: return 2; case ILOpCode.Conv_ovf_i1_un: case ILOpCode.Conv_ovf_i2_un: case ILOpCode.Conv_ovf_i4_un: case ILOpCode.Conv_ovf_i8_un: case ILOpCode.Conv_ovf_u1_un: case ILOpCode.Conv_ovf_u2_un: case ILOpCode.Conv_ovf_u4_un: case ILOpCode.Conv_ovf_u8_un: case ILOpCode.Conv_ovf_i_un: case ILOpCode.Conv_ovf_u_un: case ILOpCode.Box: case ILOpCode.Newarr: case ILOpCode.Ldlen: return 1; case ILOpCode.Ldelema: case ILOpCode.Ldelem_i1: case ILOpCode.Ldelem_u1: case ILOpCode.Ldelem_i2: case ILOpCode.Ldelem_u2: case ILOpCode.Ldelem_i4: case ILOpCode.Ldelem_u4: case ILOpCode.Ldelem_i8: case ILOpCode.Ldelem_i: case ILOpCode.Ldelem_r4: case ILOpCode.Ldelem_r8: case ILOpCode.Ldelem_ref: return 2; case ILOpCode.Stelem_i: case ILOpCode.Stelem_i1: case ILOpCode.Stelem_i2: case ILOpCode.Stelem_i4: case ILOpCode.Stelem_i8: case ILOpCode.Stelem_r4: case ILOpCode.Stelem_r8: case ILOpCode.Stelem_ref: return 3; case ILOpCode.Ldelem: return 2; case ILOpCode.Stelem: return 3; case ILOpCode.Unbox_any: case ILOpCode.Conv_ovf_i1: case ILOpCode.Conv_ovf_u1: case ILOpCode.Conv_ovf_i2: case ILOpCode.Conv_ovf_u2: case ILOpCode.Conv_ovf_i4: case ILOpCode.Conv_ovf_u4: case ILOpCode.Conv_ovf_i8: case ILOpCode.Conv_ovf_u8: case ILOpCode.Refanyval: case ILOpCode.Ckfinite: case ILOpCode.Mkrefany: return 1; case ILOpCode.Ldtoken: return 0; case ILOpCode.Conv_u2: case ILOpCode.Conv_u1: case ILOpCode.Conv_i: case ILOpCode.Conv_ovf_i: case ILOpCode.Conv_ovf_u: return 1; case ILOpCode.Add_ovf: case ILOpCode.Add_ovf_un: case ILOpCode.Mul_ovf: case ILOpCode.Mul_ovf_un: case ILOpCode.Sub_ovf: case ILOpCode.Sub_ovf_un: return 2; case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: return 0; case ILOpCode.Stind_i: return 2; case ILOpCode.Conv_u: return 1; case ILOpCode.Arglist: return 0; case ILOpCode.Ceq: case ILOpCode.Cgt: case ILOpCode.Cgt_un: case ILOpCode.Clt: case ILOpCode.Clt_un: return 2; case ILOpCode.Ldftn: return 0; case ILOpCode.Ldvirtftn: return 1; case ILOpCode.Ldarg: case ILOpCode.Ldarga: return 0; case ILOpCode.Starg: return 1; case ILOpCode.Ldloc: case ILOpCode.Ldloca: return 0; case ILOpCode.Stloc: case ILOpCode.Localloc: case ILOpCode.Endfilter: return 1; case ILOpCode.Unaligned: case ILOpCode.Volatile: case ILOpCode.Tail: return 0; case ILOpCode.Initobj: return 1; case ILOpCode.Constrained: return 0; case ILOpCode.Cpblk: case ILOpCode.Initblk: return 3; case ILOpCode.Rethrow: case ILOpCode.Sizeof: return 0; case ILOpCode.Refanytype: return 1; case ILOpCode.Readonly: return 0; } throw ExceptionUtilities.UnexpectedValue(opcode); } public static int StackPushCount(this ILOpCode opcode) { switch (opcode) { case ILOpCode.Nop: case ILOpCode.Break: return 0; case ILOpCode.Ldarg_0: case ILOpCode.Ldarg_1: case ILOpCode.Ldarg_2: case ILOpCode.Ldarg_3: case ILOpCode.Ldloc_0: case ILOpCode.Ldloc_1: case ILOpCode.Ldloc_2: case ILOpCode.Ldloc_3: return 1; case ILOpCode.Stloc_0: case ILOpCode.Stloc_1: case ILOpCode.Stloc_2: case ILOpCode.Stloc_3: return 0; case ILOpCode.Ldarg_s: case ILOpCode.Ldarga_s: return 1; case ILOpCode.Starg_s: return 0; case ILOpCode.Ldloc_s: case ILOpCode.Ldloca_s: return 1; case ILOpCode.Stloc_s: return 0; case ILOpCode.Ldnull: case ILOpCode.Ldc_i4_m1: case ILOpCode.Ldc_i4_0: case ILOpCode.Ldc_i4_1: case ILOpCode.Ldc_i4_2: case ILOpCode.Ldc_i4_3: case ILOpCode.Ldc_i4_4: case ILOpCode.Ldc_i4_5: case ILOpCode.Ldc_i4_6: case ILOpCode.Ldc_i4_7: case ILOpCode.Ldc_i4_8: case ILOpCode.Ldc_i4_s: case ILOpCode.Ldc_i4: case ILOpCode.Ldc_i8: case ILOpCode.Ldc_r4: case ILOpCode.Ldc_r8: return 1; case ILOpCode.Dup: return 2; case ILOpCode.Pop: case ILOpCode.Jmp: return 0; case ILOpCode.Call: case ILOpCode.Calli: return -1; // Variable case ILOpCode.Ret: case ILOpCode.Br_s: case ILOpCode.Brfalse_s: case ILOpCode.Brtrue_s: case ILOpCode.Beq_s: case ILOpCode.Bge_s: case ILOpCode.Bgt_s: case ILOpCode.Ble_s: case ILOpCode.Blt_s: case ILOpCode.Bne_un_s: case ILOpCode.Bge_un_s: case ILOpCode.Bgt_un_s: case ILOpCode.Ble_un_s: case ILOpCode.Blt_un_s: case ILOpCode.Br: case ILOpCode.Brfalse: case ILOpCode.Brtrue: case ILOpCode.Beq: case ILOpCode.Bge: case ILOpCode.Bgt: case ILOpCode.Ble: case ILOpCode.Blt: case ILOpCode.Bne_un: case ILOpCode.Bge_un: case ILOpCode.Bgt_un: case ILOpCode.Ble_un: case ILOpCode.Blt_un: case ILOpCode.Switch: return 0; case ILOpCode.Ldind_i1: case ILOpCode.Ldind_u1: case ILOpCode.Ldind_i2: case ILOpCode.Ldind_u2: case ILOpCode.Ldind_i4: case ILOpCode.Ldind_u4: case ILOpCode.Ldind_i8: case ILOpCode.Ldind_i: case ILOpCode.Ldind_r4: case ILOpCode.Ldind_r8: case ILOpCode.Ldind_ref: return 1; case ILOpCode.Stind_ref: case ILOpCode.Stind_i1: case ILOpCode.Stind_i2: case ILOpCode.Stind_i4: case ILOpCode.Stind_i8: case ILOpCode.Stind_r4: case ILOpCode.Stind_r8: return 0; case ILOpCode.Add: case ILOpCode.Sub: case ILOpCode.Mul: case ILOpCode.Div: case ILOpCode.Div_un: case ILOpCode.Rem: case ILOpCode.Rem_un: case ILOpCode.And: case ILOpCode.Or: case ILOpCode.Xor: case ILOpCode.Shl: case ILOpCode.Shr: case ILOpCode.Shr_un: case ILOpCode.Neg: case ILOpCode.Not: case ILOpCode.Conv_i1: case ILOpCode.Conv_i2: case ILOpCode.Conv_i4: case ILOpCode.Conv_i8: case ILOpCode.Conv_r4: case ILOpCode.Conv_r8: case ILOpCode.Conv_u4: case ILOpCode.Conv_u8: return 1; case ILOpCode.Callvirt: return -1; // Variable case ILOpCode.Cpobj: return 0; case ILOpCode.Ldobj: case ILOpCode.Ldstr: case ILOpCode.Newobj: case ILOpCode.Castclass: case ILOpCode.Isinst: case ILOpCode.Conv_r_un: case ILOpCode.Unbox: return 1; case ILOpCode.Throw: return 0; case ILOpCode.Ldfld: case ILOpCode.Ldflda: return 1; case ILOpCode.Stfld: return 0; case ILOpCode.Ldsfld: case ILOpCode.Ldsflda: return 1; case ILOpCode.Stsfld: case ILOpCode.Stobj: return 0; case ILOpCode.Conv_ovf_i1_un: case ILOpCode.Conv_ovf_i2_un: case ILOpCode.Conv_ovf_i4_un: case ILOpCode.Conv_ovf_i8_un: case ILOpCode.Conv_ovf_u1_un: case ILOpCode.Conv_ovf_u2_un: case ILOpCode.Conv_ovf_u4_un: case ILOpCode.Conv_ovf_u8_un: case ILOpCode.Conv_ovf_i_un: case ILOpCode.Conv_ovf_u_un: case ILOpCode.Box: case ILOpCode.Newarr: case ILOpCode.Ldlen: case ILOpCode.Ldelema: case ILOpCode.Ldelem_i1: case ILOpCode.Ldelem_u1: case ILOpCode.Ldelem_i2: case ILOpCode.Ldelem_u2: case ILOpCode.Ldelem_i4: case ILOpCode.Ldelem_u4: case ILOpCode.Ldelem_i8: case ILOpCode.Ldelem_i: case ILOpCode.Ldelem_r4: case ILOpCode.Ldelem_r8: case ILOpCode.Ldelem_ref: return 1; case ILOpCode.Stelem_i: case ILOpCode.Stelem_i1: case ILOpCode.Stelem_i2: case ILOpCode.Stelem_i4: case ILOpCode.Stelem_i8: case ILOpCode.Stelem_r4: case ILOpCode.Stelem_r8: case ILOpCode.Stelem_ref: return 0; case ILOpCode.Ldelem: return 1; case ILOpCode.Stelem: return 0; case ILOpCode.Unbox_any: case ILOpCode.Conv_ovf_i1: case ILOpCode.Conv_ovf_u1: case ILOpCode.Conv_ovf_i2: case ILOpCode.Conv_ovf_u2: case ILOpCode.Conv_ovf_i4: case ILOpCode.Conv_ovf_u4: case ILOpCode.Conv_ovf_i8: case ILOpCode.Conv_ovf_u8: case ILOpCode.Refanyval: case ILOpCode.Ckfinite: case ILOpCode.Mkrefany: case ILOpCode.Ldtoken: case ILOpCode.Conv_u2: case ILOpCode.Conv_u1: case ILOpCode.Conv_i: case ILOpCode.Conv_ovf_i: case ILOpCode.Conv_ovf_u: case ILOpCode.Add_ovf: case ILOpCode.Add_ovf_un: case ILOpCode.Mul_ovf: case ILOpCode.Mul_ovf_un: case ILOpCode.Sub_ovf: case ILOpCode.Sub_ovf_un: return 1; case ILOpCode.Endfinally: case ILOpCode.Leave: case ILOpCode.Leave_s: case ILOpCode.Stind_i: return 0; case ILOpCode.Conv_u: case ILOpCode.Arglist: case ILOpCode.Ceq: case ILOpCode.Cgt: case ILOpCode.Cgt_un: case ILOpCode.Clt: case ILOpCode.Clt_un: case ILOpCode.Ldftn: case ILOpCode.Ldvirtftn: case ILOpCode.Ldarg: case ILOpCode.Ldarga: return 1; case ILOpCode.Starg: return 0; case ILOpCode.Ldloc: case ILOpCode.Ldloca: return 1; case ILOpCode.Stloc: return 0; case ILOpCode.Localloc: return 1; case ILOpCode.Endfilter: case ILOpCode.Unaligned: case ILOpCode.Volatile: case ILOpCode.Tail: case ILOpCode.Initobj: case ILOpCode.Constrained: case ILOpCode.Cpblk: case ILOpCode.Initblk: case ILOpCode.Rethrow: return 0; case ILOpCode.Sizeof: case ILOpCode.Refanytype: return 1; case ILOpCode.Readonly: return 0; } throw ExceptionUtilities.UnexpectedValue(opcode); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./eng/common/native/CommonLibrary.psm1
<# .SYNOPSIS Helper module to install an archive to a directory .DESCRIPTION Helper module to download and extract an archive to a specified directory .PARAMETER Uri Uri of artifact to download .PARAMETER InstallDirectory Directory to extract artifact contents to .PARAMETER Force Force download / extraction if file or contents already exist. Default = False .PARAMETER DownloadRetries Total number of retry attempts. Default = 5 .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds. Default = 30 .NOTES Returns False if download or extraction fail, True otherwise #> function DownloadAndExtract { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Uri, [Parameter(Mandatory=$True)] [string] $InstallDirectory, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30 ) # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq "Continue" $TempToolPath = CommonLibrary\Get-TempPathFilename -Path $Uri # Download native tool $DownloadStatus = CommonLibrary\Get-File -Uri $Uri ` -Path $TempToolPath ` -DownloadRetries $DownloadRetries ` -RetryWaitTimeInSeconds $RetryWaitTimeInSeconds ` -Force:$Force ` -Verbose:$Verbose if ($DownloadStatus -Eq $False) { Write-Error "Download failed from $Uri" return $False } # Extract native tool $UnzipStatus = CommonLibrary\Expand-Zip -ZipPath $TempToolPath ` -OutputDirectory $InstallDirectory ` -Force:$Force ` -Verbose:$Verbose if ($UnzipStatus -Eq $False) { # Retry Download one more time with Force=true $DownloadRetryStatus = CommonLibrary\Get-File -Uri $Uri ` -Path $TempToolPath ` -DownloadRetries 1 ` -RetryWaitTimeInSeconds $RetryWaitTimeInSeconds ` -Force:$True ` -Verbose:$Verbose if ($DownloadRetryStatus -Eq $False) { Write-Error "Last attempt of download failed as well" return $False } # Retry unzip again one more time with Force=true $UnzipRetryStatus = CommonLibrary\Expand-Zip -ZipPath $TempToolPath ` -OutputDirectory $InstallDirectory ` -Force:$True ` -Verbose:$Verbose if ($UnzipRetryStatus -Eq $False) { Write-Error "Last attempt of unzip failed as well" # Clean up partial zips and extracts if (Test-Path $TempToolPath) { Remove-Item $TempToolPath -Force } if (Test-Path $InstallDirectory) { Remove-Item $InstallDirectory -Force -Recurse } return $False } } return $True } <# .SYNOPSIS Download a file, retry on failure .DESCRIPTION Download specified file and retry if attempt fails .PARAMETER Uri Uri of file to download. If Uri is a local path, the file will be copied instead of downloaded .PARAMETER Path Path to download or copy uri file to .PARAMETER Force Overwrite existing file if present. Default = False .PARAMETER DownloadRetries Total number of retry attempts. Default = 5 .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds Default = 30 #> function Get-File { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Uri, [Parameter(Mandatory=$True)] [string] $Path, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [switch] $Force = $False ) $Attempt = 0 if ($Force) { if (Test-Path $Path) { Remove-Item $Path -Force } } if (Test-Path $Path) { Write-Host "File '$Path' already exists, skipping download" return $True } $DownloadDirectory = Split-Path -ErrorAction Ignore -Path "$Path" -Parent if (-Not (Test-Path $DownloadDirectory)) { New-Item -path $DownloadDirectory -force -itemType "Directory" | Out-Null } $TempPath = "$Path.tmp" if (Test-Path -IsValid -Path $Uri) { Write-Verbose "'$Uri' is a file path, copying temporarily to '$TempPath'" Copy-Item -Path $Uri -Destination $TempPath Write-Verbose "Moving temporary file to '$Path'" Move-Item -Path $TempPath -Destination $Path return $? } else { Write-Verbose "Downloading $Uri" # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' while($Attempt -Lt $DownloadRetries) { try { Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $TempPath Write-Verbose "Downloaded to temporary location '$TempPath'" Move-Item -Path $TempPath -Destination $Path Write-Verbose "Moved temporary file to '$Path'" return $True } catch { $Attempt++ if ($Attempt -Lt $DownloadRetries) { $AttemptsLeft = $DownloadRetries - $Attempt Write-Warning "Download failed, $AttemptsLeft attempts remaining, will retry in $RetryWaitTimeInSeconds seconds" Start-Sleep -Seconds $RetryWaitTimeInSeconds } else { Write-Error $_ Write-Error $_.Exception } } } } return $False } <# .SYNOPSIS Generate a shim for a native tool .DESCRIPTION Creates a wrapper script (shim) that passes arguments forward to native tool assembly .PARAMETER ShimName The name of the shim .PARAMETER ShimDirectory The directory where shims are stored .PARAMETER ToolFilePath Path to file that shim forwards to .PARAMETER Force Replace shim if already present. Default = False .NOTES Returns $True if generating shim succeeds, $False otherwise #> function New-ScriptShim { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $ShimName, [Parameter(Mandatory=$True)] [string] $ShimDirectory, [Parameter(Mandatory=$True)] [string] $ToolFilePath, [Parameter(Mandatory=$True)] [string] $BaseUri, [switch] $Force ) try { Write-Verbose "Generating '$ShimName' shim" if (-Not (Test-Path $ToolFilePath)){ Write-Error "Specified tool file path '$ToolFilePath' does not exist" return $False } # WinShimmer is a small .NET Framework program that creates .exe shims to bootstrapped programs # Many of the checks for installed programs expect a .exe extension for Windows tools, rather # than a .bat or .cmd file. # Source: https://github.com/dotnet/arcade/tree/master/src/WinShimmer if (-Not (Test-Path "$ShimDirectory\WinShimmer\winshimmer.exe")) { $InstallStatus = DownloadAndExtract -Uri "$BaseUri/windows/winshimmer/WinShimmer.zip" ` -InstallDirectory $ShimDirectory\WinShimmer ` -Force:$Force ` -DownloadRetries 2 ` -RetryWaitTimeInSeconds 5 ` -Verbose:$Verbose } if ((Test-Path (Join-Path $ShimDirectory "$ShimName.exe"))) { Write-Host "$ShimName.exe already exists; replacing..." Remove-Item (Join-Path $ShimDirectory "$ShimName.exe") } & "$ShimDirectory\WinShimmer\winshimmer.exe" $ShimName $ToolFilePath $ShimDirectory return $True } catch { Write-Host $_ Write-Host $_.Exception return $False } } <# .SYNOPSIS Returns the machine architecture of the host machine .NOTES Returns 'x64' on 64 bit machines Returns 'x86' on 32 bit machines #> function Get-MachineArchitecture { $ProcessorArchitecture = $Env:PROCESSOR_ARCHITECTURE $ProcessorArchitectureW6432 = $Env:PROCESSOR_ARCHITEW6432 if($ProcessorArchitecture -Eq "X86") { if(($ProcessorArchitectureW6432 -Eq "") -Or ($ProcessorArchitectureW6432 -Eq "X86")) { return "x86" } $ProcessorArchitecture = $ProcessorArchitectureW6432 } if (($ProcessorArchitecture -Eq "AMD64") -Or ($ProcessorArchitecture -Eq "IA64") -Or ($ProcessorArchitecture -Eq "ARM64")) { return "x64" } return "x86" } <# .SYNOPSIS Get the name of a temporary folder under the native install directory #> function Get-TempDirectory { return Join-Path (Get-NativeInstallDirectory) "temp/" } function Get-TempPathFilename { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Path ) $TempDir = CommonLibrary\Get-TempDirectory $TempFilename = Split-Path $Path -leaf $TempPath = Join-Path $TempDir $TempFilename return $TempPath } <# .SYNOPSIS Returns the base directory to use for native tool installation .NOTES Returns the value of the NETCOREENG_INSTALL_DIRECTORY if that environment variable is set, or otherwise returns an install directory under the %USERPROFILE% #> function Get-NativeInstallDirectory { $InstallDir = $Env:NETCOREENG_INSTALL_DIRECTORY if (!$InstallDir) { $InstallDir = Join-Path $Env:USERPROFILE ".netcoreeng/native/" } return $InstallDir } <# .SYNOPSIS Unzip an archive .DESCRIPTION Powershell module to unzip an archive to a specified directory .PARAMETER ZipPath (Required) Path to archive to unzip .PARAMETER OutputDirectory (Required) Output directory for archive contents .PARAMETER Force Overwrite output directory contents if they already exist .NOTES - Returns True and does not perform an extraction if output directory already exists but Overwrite is not True. - Returns True if unzip operation is successful - Returns False if Overwrite is True and it is unable to remove contents of OutputDirectory - Returns False if unable to extract zip archive #> function Expand-Zip { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $ZipPath, [Parameter(Mandatory=$True)] [string] $OutputDirectory, [switch] $Force ) Write-Verbose "Extracting '$ZipPath' to '$OutputDirectory'" try { if ((Test-Path $OutputDirectory) -And (-Not $Force)) { Write-Host "Directory '$OutputDirectory' already exists, skipping extract" return $True } if (Test-Path $OutputDirectory) { Write-Verbose "'Force' is 'True', but '$OutputDirectory' exists, removing directory" Remove-Item $OutputDirectory -Force -Recurse if ($? -Eq $False) { Write-Error "Unable to remove '$OutputDirectory'" return $False } } $TempOutputDirectory = Join-Path "$(Split-Path -Parent $OutputDirectory)" "$(Split-Path -Leaf $OutputDirectory).tmp" if (Test-Path $TempOutputDirectory) { Remove-Item $TempOutputDirectory -Force -Recurse } New-Item -Path $TempOutputDirectory -Force -ItemType "Directory" | Out-Null Add-Type -assembly "system.io.compression.filesystem" [io.compression.zipfile]::ExtractToDirectory("$ZipPath", "$TempOutputDirectory") if ($? -Eq $False) { Write-Error "Unable to extract '$ZipPath'" return $False } Move-Item -Path $TempOutputDirectory -Destination $OutputDirectory } catch { Write-Host $_ Write-Host $_.Exception return $False } return $True } export-modulemember -function DownloadAndExtract export-modulemember -function Expand-Zip export-modulemember -function Get-File export-modulemember -function Get-MachineArchitecture export-modulemember -function Get-NativeInstallDirectory export-modulemember -function Get-TempDirectory export-modulemember -function Get-TempPathFilename export-modulemember -function New-ScriptShim
<# .SYNOPSIS Helper module to install an archive to a directory .DESCRIPTION Helper module to download and extract an archive to a specified directory .PARAMETER Uri Uri of artifact to download .PARAMETER InstallDirectory Directory to extract artifact contents to .PARAMETER Force Force download / extraction if file or contents already exist. Default = False .PARAMETER DownloadRetries Total number of retry attempts. Default = 5 .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds. Default = 30 .NOTES Returns False if download or extraction fail, True otherwise #> function DownloadAndExtract { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Uri, [Parameter(Mandatory=$True)] [string] $InstallDirectory, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30 ) # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq "Continue" $TempToolPath = CommonLibrary\Get-TempPathFilename -Path $Uri # Download native tool $DownloadStatus = CommonLibrary\Get-File -Uri $Uri ` -Path $TempToolPath ` -DownloadRetries $DownloadRetries ` -RetryWaitTimeInSeconds $RetryWaitTimeInSeconds ` -Force:$Force ` -Verbose:$Verbose if ($DownloadStatus -Eq $False) { Write-Error "Download failed from $Uri" return $False } # Extract native tool $UnzipStatus = CommonLibrary\Expand-Zip -ZipPath $TempToolPath ` -OutputDirectory $InstallDirectory ` -Force:$Force ` -Verbose:$Verbose if ($UnzipStatus -Eq $False) { # Retry Download one more time with Force=true $DownloadRetryStatus = CommonLibrary\Get-File -Uri $Uri ` -Path $TempToolPath ` -DownloadRetries 1 ` -RetryWaitTimeInSeconds $RetryWaitTimeInSeconds ` -Force:$True ` -Verbose:$Verbose if ($DownloadRetryStatus -Eq $False) { Write-Error "Last attempt of download failed as well" return $False } # Retry unzip again one more time with Force=true $UnzipRetryStatus = CommonLibrary\Expand-Zip -ZipPath $TempToolPath ` -OutputDirectory $InstallDirectory ` -Force:$True ` -Verbose:$Verbose if ($UnzipRetryStatus -Eq $False) { Write-Error "Last attempt of unzip failed as well" # Clean up partial zips and extracts if (Test-Path $TempToolPath) { Remove-Item $TempToolPath -Force } if (Test-Path $InstallDirectory) { Remove-Item $InstallDirectory -Force -Recurse } return $False } } return $True } <# .SYNOPSIS Download a file, retry on failure .DESCRIPTION Download specified file and retry if attempt fails .PARAMETER Uri Uri of file to download. If Uri is a local path, the file will be copied instead of downloaded .PARAMETER Path Path to download or copy uri file to .PARAMETER Force Overwrite existing file if present. Default = False .PARAMETER DownloadRetries Total number of retry attempts. Default = 5 .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds Default = 30 #> function Get-File { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Uri, [Parameter(Mandatory=$True)] [string] $Path, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [switch] $Force = $False ) $Attempt = 0 if ($Force) { if (Test-Path $Path) { Remove-Item $Path -Force } } if (Test-Path $Path) { Write-Host "File '$Path' already exists, skipping download" return $True } $DownloadDirectory = Split-Path -ErrorAction Ignore -Path "$Path" -Parent if (-Not (Test-Path $DownloadDirectory)) { New-Item -path $DownloadDirectory -force -itemType "Directory" | Out-Null } $TempPath = "$Path.tmp" if (Test-Path -IsValid -Path $Uri) { Write-Verbose "'$Uri' is a file path, copying temporarily to '$TempPath'" Copy-Item -Path $Uri -Destination $TempPath Write-Verbose "Moving temporary file to '$Path'" Move-Item -Path $TempPath -Destination $Path return $? } else { Write-Verbose "Downloading $Uri" # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' while($Attempt -Lt $DownloadRetries) { try { Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $TempPath Write-Verbose "Downloaded to temporary location '$TempPath'" Move-Item -Path $TempPath -Destination $Path Write-Verbose "Moved temporary file to '$Path'" return $True } catch { $Attempt++ if ($Attempt -Lt $DownloadRetries) { $AttemptsLeft = $DownloadRetries - $Attempt Write-Warning "Download failed, $AttemptsLeft attempts remaining, will retry in $RetryWaitTimeInSeconds seconds" Start-Sleep -Seconds $RetryWaitTimeInSeconds } else { Write-Error $_ Write-Error $_.Exception } } } } return $False } <# .SYNOPSIS Generate a shim for a native tool .DESCRIPTION Creates a wrapper script (shim) that passes arguments forward to native tool assembly .PARAMETER ShimName The name of the shim .PARAMETER ShimDirectory The directory where shims are stored .PARAMETER ToolFilePath Path to file that shim forwards to .PARAMETER Force Replace shim if already present. Default = False .NOTES Returns $True if generating shim succeeds, $False otherwise #> function New-ScriptShim { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $ShimName, [Parameter(Mandatory=$True)] [string] $ShimDirectory, [Parameter(Mandatory=$True)] [string] $ToolFilePath, [Parameter(Mandatory=$True)] [string] $BaseUri, [switch] $Force ) try { Write-Verbose "Generating '$ShimName' shim" if (-Not (Test-Path $ToolFilePath)){ Write-Error "Specified tool file path '$ToolFilePath' does not exist" return $False } # WinShimmer is a small .NET Framework program that creates .exe shims to bootstrapped programs # Many of the checks for installed programs expect a .exe extension for Windows tools, rather # than a .bat or .cmd file. # Source: https://github.com/dotnet/arcade/tree/master/src/WinShimmer if (-Not (Test-Path "$ShimDirectory\WinShimmer\winshimmer.exe")) { $InstallStatus = DownloadAndExtract -Uri "$BaseUri/windows/winshimmer/WinShimmer.zip" ` -InstallDirectory $ShimDirectory\WinShimmer ` -Force:$Force ` -DownloadRetries 2 ` -RetryWaitTimeInSeconds 5 ` -Verbose:$Verbose } if ((Test-Path (Join-Path $ShimDirectory "$ShimName.exe"))) { Write-Host "$ShimName.exe already exists; replacing..." Remove-Item (Join-Path $ShimDirectory "$ShimName.exe") } & "$ShimDirectory\WinShimmer\winshimmer.exe" $ShimName $ToolFilePath $ShimDirectory return $True } catch { Write-Host $_ Write-Host $_.Exception return $False } } <# .SYNOPSIS Returns the machine architecture of the host machine .NOTES Returns 'x64' on 64 bit machines Returns 'x86' on 32 bit machines #> function Get-MachineArchitecture { $ProcessorArchitecture = $Env:PROCESSOR_ARCHITECTURE $ProcessorArchitectureW6432 = $Env:PROCESSOR_ARCHITEW6432 if($ProcessorArchitecture -Eq "X86") { if(($ProcessorArchitectureW6432 -Eq "") -Or ($ProcessorArchitectureW6432 -Eq "X86")) { return "x86" } $ProcessorArchitecture = $ProcessorArchitectureW6432 } if (($ProcessorArchitecture -Eq "AMD64") -Or ($ProcessorArchitecture -Eq "IA64") -Or ($ProcessorArchitecture -Eq "ARM64")) { return "x64" } return "x86" } <# .SYNOPSIS Get the name of a temporary folder under the native install directory #> function Get-TempDirectory { return Join-Path (Get-NativeInstallDirectory) "temp/" } function Get-TempPathFilename { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $Path ) $TempDir = CommonLibrary\Get-TempDirectory $TempFilename = Split-Path $Path -leaf $TempPath = Join-Path $TempDir $TempFilename return $TempPath } <# .SYNOPSIS Returns the base directory to use for native tool installation .NOTES Returns the value of the NETCOREENG_INSTALL_DIRECTORY if that environment variable is set, or otherwise returns an install directory under the %USERPROFILE% #> function Get-NativeInstallDirectory { $InstallDir = $Env:NETCOREENG_INSTALL_DIRECTORY if (!$InstallDir) { $InstallDir = Join-Path $Env:USERPROFILE ".netcoreeng/native/" } return $InstallDir } <# .SYNOPSIS Unzip an archive .DESCRIPTION Powershell module to unzip an archive to a specified directory .PARAMETER ZipPath (Required) Path to archive to unzip .PARAMETER OutputDirectory (Required) Output directory for archive contents .PARAMETER Force Overwrite output directory contents if they already exist .NOTES - Returns True and does not perform an extraction if output directory already exists but Overwrite is not True. - Returns True if unzip operation is successful - Returns False if Overwrite is True and it is unable to remove contents of OutputDirectory - Returns False if unable to extract zip archive #> function Expand-Zip { [CmdletBinding(PositionalBinding=$false)] Param ( [Parameter(Mandatory=$True)] [string] $ZipPath, [Parameter(Mandatory=$True)] [string] $OutputDirectory, [switch] $Force ) Write-Verbose "Extracting '$ZipPath' to '$OutputDirectory'" try { if ((Test-Path $OutputDirectory) -And (-Not $Force)) { Write-Host "Directory '$OutputDirectory' already exists, skipping extract" return $True } if (Test-Path $OutputDirectory) { Write-Verbose "'Force' is 'True', but '$OutputDirectory' exists, removing directory" Remove-Item $OutputDirectory -Force -Recurse if ($? -Eq $False) { Write-Error "Unable to remove '$OutputDirectory'" return $False } } $TempOutputDirectory = Join-Path "$(Split-Path -Parent $OutputDirectory)" "$(Split-Path -Leaf $OutputDirectory).tmp" if (Test-Path $TempOutputDirectory) { Remove-Item $TempOutputDirectory -Force -Recurse } New-Item -Path $TempOutputDirectory -Force -ItemType "Directory" | Out-Null Add-Type -assembly "system.io.compression.filesystem" [io.compression.zipfile]::ExtractToDirectory("$ZipPath", "$TempOutputDirectory") if ($? -Eq $False) { Write-Error "Unable to extract '$ZipPath'" return $False } Move-Item -Path $TempOutputDirectory -Destination $OutputDirectory } catch { Write-Host $_ Write-Host $_.Exception return $False } return $True } export-modulemember -function DownloadAndExtract export-modulemember -function Expand-Zip export-modulemember -function Get-File export-modulemember -function Get-MachineArchitecture export-modulemember -function Get-NativeInstallDirectory export-modulemember -function Get-TempDirectory export-modulemember -function Get-TempPathFilename export-modulemember -function New-ScriptShim
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/Emit/SemanticEdit.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Symbols; using Roslyn.Utilities; using System; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Describes a symbol edit between two compilations. /// For example, an addition of a method, an update of a method, removal of a type, etc. /// </summary> public readonly struct SemanticEdit : IEquatable<SemanticEdit> { /// <summary> /// The type of edit. /// </summary> public SemanticEditKind Kind { get; } /// <summary> /// The symbol from the earlier compilation, /// or null if the edit represents an addition. /// </summary> public ISymbol? OldSymbol { get; } /// <summary> /// The symbol from the later compilation, /// or null if the edit represents a deletion. /// </summary> public ISymbol? NewSymbol { get; } /// <summary> /// A map from syntax node in the later compilation to syntax node in the previous compilation, /// or null if <see cref="PreserveLocalVariables"/> is false and the map is not needed or /// the source of the current method is the same as the source of the previous method. /// </summary> /// <remarks> /// The map does not need to map all syntax nodes in the active method, only those syntax nodes /// that declare a local or generate a long lived local. /// </remarks> public Func<SyntaxNode, SyntaxNode?>? SyntaxMap { get; } /// <summary> /// True if the edit is an update of the active method and local values /// should be preserved; false otherwise. /// </summary> public bool PreserveLocalVariables { get; } /// <summary> /// Initializes an instance of <see cref="SemanticEdit"/>. /// </summary> /// <param name="kind">The type of edit.</param> /// <param name="oldSymbol"> /// The symbol from the earlier compilation, or null if the edit represents an addition. /// </param> /// <param name="newSymbol"> /// The symbol from the later compilation, or null if the edit represents a deletion. /// </param> /// <param name="syntaxMap"> /// A map from syntax node in the later compilation to syntax node in the previous compilation, /// or null if <paramref name="preserveLocalVariables"/> is false and the map is not needed or /// the source of the current method is the same as the source of the previous method. /// </param> /// <param name="preserveLocalVariables"> /// True if the edit is an update of an active method and local values should be preserved; false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="oldSymbol"/> or <paramref name="newSymbol"/> is null and the edit isn't a <see cref="SemanticEditKind.Insert"/> or <see cref="SemanticEditKind.Delete"/>, respectively. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="kind"/> is not a valid kind. /// </exception> public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap = null, bool preserveLocalVariables = false) { if (oldSymbol == null && kind is not (SemanticEditKind.Insert or SemanticEditKind.Replace)) { throw new ArgumentNullException(nameof(oldSymbol)); } if (newSymbol == null && kind != SemanticEditKind.Delete) { throw new ArgumentNullException(nameof(newSymbol)); } if (kind <= SemanticEditKind.None || kind > SemanticEditKind.Replace) { throw new ArgumentOutOfRangeException(nameof(kind)); } Kind = kind; OldSymbol = oldSymbol; NewSymbol = newSymbol; PreserveLocalVariables = preserveLocalVariables; SyntaxMap = syntaxMap; } internal static SemanticEdit Create(SemanticEditKind kind, ISymbolInternal oldSymbol, ISymbolInternal newSymbol, Func<SyntaxNode, SyntaxNode>? syntaxMap = null, bool preserveLocalVariables = false) => new SemanticEdit(kind, oldSymbol?.GetISymbol(), newSymbol?.GetISymbol(), syntaxMap, preserveLocalVariables); public override int GetHashCode() => Hash.Combine(OldSymbol, Hash.Combine(NewSymbol, (int)Kind)); public override bool Equals(object? obj) => obj is SemanticEdit other && Equals(other); public bool Equals(SemanticEdit other) => Kind == other.Kind && (OldSymbol == null ? other.OldSymbol == null : OldSymbol.Equals(other.OldSymbol)) && (NewSymbol == null ? other.NewSymbol == null : NewSymbol.Equals(other.NewSymbol)); public static bool operator ==(SemanticEdit left, SemanticEdit right) => left.Equals(right); public static bool operator !=(SemanticEdit left, SemanticEdit right) => !(left == right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; using System; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Describes a symbol edit between two compilations. /// For example, an addition of a method, an update of a method, removal of a type, etc. /// </summary> public readonly struct SemanticEdit : IEquatable<SemanticEdit> { /// <summary> /// The type of edit. /// </summary> public SemanticEditKind Kind { get; } /// <summary> /// The symbol from the earlier compilation, /// or null if the edit represents an addition. /// </summary> public ISymbol? OldSymbol { get; } /// <summary> /// The symbol from the later compilation, /// or null if the edit represents a deletion. /// </summary> public ISymbol? NewSymbol { get; } /// <summary> /// A map from syntax node in the later compilation to syntax node in the previous compilation, /// or null if <see cref="PreserveLocalVariables"/> is false and the map is not needed or /// the source of the current method is the same as the source of the previous method. /// </summary> /// <remarks> /// The map does not need to map all syntax nodes in the active method, only those syntax nodes /// that declare a local or generate a long lived local. /// </remarks> public Func<SyntaxNode, SyntaxNode?>? SyntaxMap { get; } /// <summary> /// True if the edit is an update of the active method and local values /// should be preserved; false otherwise. /// </summary> public bool PreserveLocalVariables { get; } /// <summary> /// Initializes an instance of <see cref="SemanticEdit"/>. /// </summary> /// <param name="kind">The type of edit.</param> /// <param name="oldSymbol"> /// The symbol from the earlier compilation, or null if the edit represents an addition. /// </param> /// <param name="newSymbol"> /// The symbol from the later compilation, or null if the edit represents a deletion. /// </param> /// <param name="syntaxMap"> /// A map from syntax node in the later compilation to syntax node in the previous compilation, /// or null if <paramref name="preserveLocalVariables"/> is false and the map is not needed or /// the source of the current method is the same as the source of the previous method. /// </param> /// <param name="preserveLocalVariables"> /// True if the edit is an update of an active method and local values should be preserved; false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="oldSymbol"/> or <paramref name="newSymbol"/> is null and the edit isn't a <see cref="SemanticEditKind.Insert"/> or <see cref="SemanticEditKind.Delete"/>, respectively. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="kind"/> is not a valid kind. /// </exception> public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap = null, bool preserveLocalVariables = false) { if (oldSymbol == null && kind is not (SemanticEditKind.Insert or SemanticEditKind.Replace)) { throw new ArgumentNullException(nameof(oldSymbol)); } if (newSymbol == null && kind != SemanticEditKind.Delete) { throw new ArgumentNullException(nameof(newSymbol)); } if (kind <= SemanticEditKind.None || kind > SemanticEditKind.Replace) { throw new ArgumentOutOfRangeException(nameof(kind)); } Kind = kind; OldSymbol = oldSymbol; NewSymbol = newSymbol; PreserveLocalVariables = preserveLocalVariables; SyntaxMap = syntaxMap; } internal static SemanticEdit Create(SemanticEditKind kind, ISymbolInternal oldSymbol, ISymbolInternal newSymbol, Func<SyntaxNode, SyntaxNode>? syntaxMap = null, bool preserveLocalVariables = false) => new SemanticEdit(kind, oldSymbol?.GetISymbol(), newSymbol?.GetISymbol(), syntaxMap, preserveLocalVariables); public override int GetHashCode() => Hash.Combine(OldSymbol, Hash.Combine(NewSymbol, (int)Kind)); public override bool Equals(object? obj) => obj is SemanticEdit other && Equals(other); public bool Equals(SemanticEdit other) => Kind == other.Kind && (OldSymbol == null ? other.OldSymbol == null : OldSymbol.Equals(other.OldSymbol)) && (NewSymbol == null ? other.NewSymbol == null : NewSymbol.Equals(other.NewSymbol)); public static bool operator ==(SemanticEdit left, SemanticEdit right) => left.Equals(right); public static bool operator !=(SemanticEdit left, SemanticEdit right) => !(left == right); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/VisualBasic/Portable/CodeCleanup/VisualBasicCodeCleanupService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedVariable Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup <ExportLanguageService(GetType(ICodeCleanupService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCodeCleanupService Inherits AbstractCodeCleanupService ''' <summary> ''' Maps format document code cleanup options to DiagnosticId[] ''' </summary> Private Shared ReadOnly s_diagnosticSets As ImmutableArray(Of DiagnosticSet) = ImmutableArray.Create( New DiagnosticSet(VBFeaturesResources.Apply_Me_qualification_preferences, IDEDiagnosticIds.AddQualificationDiagnosticId, IDEDiagnosticIds.RemoveQualificationDiagnosticId), New DiagnosticSet(AnalyzersResources.Add_accessibility_modifiers, IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId), New DiagnosticSet(FeaturesResources.Sort_accessibility_modifiers, IDEDiagnosticIds.OrderModifiersDiagnosticId), New DiagnosticSet(VBFeaturesResources.Make_private_field_ReadOnly_when_possible, IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unnecessary_casts, IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unused_variables, VisualBasicRemoveUnusedVariableCodeFixProvider.BC42024), New DiagnosticSet(FeaturesResources.Apply_object_collection_initialization_preferences, IDEDiagnosticIds.UseObjectInitializerDiagnosticId, IDEDiagnosticIds.UseCollectionInitializerDiagnosticId), New DiagnosticSet(VBFeaturesResources.Apply_Imports_directive_placement_preferences, IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId), New DiagnosticSet(FeaturesResources.Apply_file_header_preferences, IDEDiagnosticIds.FileHeaderMismatch)) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(codeFixService As ICodeFixService) MyBase.New(codeFixService) End Sub Protected Overrides ReadOnly Property OrganizeImportsDescription As String = VBFeaturesResources.Organize_Imports Protected Overrides Function GetDiagnosticSets() As ImmutableArray(Of DiagnosticSet) Return s_diagnosticSets End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedVariable Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup <ExportLanguageService(GetType(ICodeCleanupService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCodeCleanupService Inherits AbstractCodeCleanupService ''' <summary> ''' Maps format document code cleanup options to DiagnosticId[] ''' </summary> Private Shared ReadOnly s_diagnosticSets As ImmutableArray(Of DiagnosticSet) = ImmutableArray.Create( New DiagnosticSet(VBFeaturesResources.Apply_Me_qualification_preferences, IDEDiagnosticIds.AddQualificationDiagnosticId, IDEDiagnosticIds.RemoveQualificationDiagnosticId), New DiagnosticSet(AnalyzersResources.Add_accessibility_modifiers, IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId), New DiagnosticSet(FeaturesResources.Sort_accessibility_modifiers, IDEDiagnosticIds.OrderModifiersDiagnosticId), New DiagnosticSet(VBFeaturesResources.Make_private_field_ReadOnly_when_possible, IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unnecessary_casts, IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unused_variables, VisualBasicRemoveUnusedVariableCodeFixProvider.BC42024), New DiagnosticSet(FeaturesResources.Apply_object_collection_initialization_preferences, IDEDiagnosticIds.UseObjectInitializerDiagnosticId, IDEDiagnosticIds.UseCollectionInitializerDiagnosticId), New DiagnosticSet(VBFeaturesResources.Apply_Imports_directive_placement_preferences, IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId), New DiagnosticSet(FeaturesResources.Apply_file_header_preferences, IDEDiagnosticIds.FileHeaderMismatch)) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(codeFixService As ICodeFixService) MyBase.New(codeFixService) End Sub Protected Overrides ReadOnly Property OrganizeImportsDescription As String = VBFeaturesResources.Organize_Imports Protected Overrides Function GetDiagnosticSets() As ImmutableArray(Of DiagnosticSet) Return s_diagnosticSets End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Syntax/ParameterListSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ParameterListSyntax { internal int ParameterCount { get { int count = 0; foreach (ParameterSyntax parameter in this.Parameters) { // __arglist does not affect the parameter count. if (!parameter.IsArgList) { count++; } } return count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ParameterListSyntax { internal int ParameterCount { get { int count = 0; foreach (ParameterSyntax parameter in this.Parameters) { // __arglist does not affect the parameter count. if (!parameter.IsArgList) { count++; } } return count; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/CodeModel/IProjectCodeModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface IProjectCodeModel { EnvDTE.FileCodeModel GetOrCreateFileCodeModel(string filePath, object parent); EnvDTE.CodeModel GetOrCreateRootCodeModel(Project parent); void OnSourceFileRemoved(string fileName); void OnSourceFileRenaming(string filePath, string newFilePath); void OnProjectClosed(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface IProjectCodeModel { EnvDTE.FileCodeModel GetOrCreateFileCodeModel(string filePath, object parent); EnvDTE.CodeModel GetOrCreateRootCodeModel(Project parent); void OnSourceFileRemoved(string fileName); void OnSourceFileRenaming(string filePath, string newFilePath); void OnProjectClosed(); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Rebuild/VisualBasicCompilationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Rebuild { public sealed class VisualBasicCompilationFactory : CompilationFactory { public new VisualBasicCompilationOptions CompilationOptions { get; } public new VisualBasicParseOptions ParseOptions => CompilationOptions.ParseOptions; protected override ParseOptions CommonParseOptions => ParseOptions; protected override CompilationOptions CommonCompilationOptions => CompilationOptions; private VisualBasicCompilationFactory( string assemblyFileName, CompilationOptionsReader optionsReader, VisualBasicCompilationOptions compilationOptions) : base(assemblyFileName, optionsReader) { CompilationOptions = compilationOptions; } internal static new VisualBasicCompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) { Debug.Assert(optionsReader.GetLanguageName() == LanguageNames.VisualBasic); var compilationOptions = CreateVisualBasicCompilationOptions(assemblyFileName, optionsReader); return new VisualBasicCompilationFactory(assemblyFileName, optionsReader, compilationOptions); } public override SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText) => VisualBasicSyntaxTree.ParseText(sourceText, ParseOptions, filePath); public override Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences) => VisualBasicCompilation.Create( Path.GetFileNameWithoutExtension(AssemblyFileName), syntaxTrees: syntaxTrees, references: metadataReferences, options: CompilationOptions); private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(string assemblyFileName, CompilationOptionsReader optionsReader) { var pdbOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); pdbOptions.TryGetUniqueOption(CompilationOptionNames.GlobalNamespaces, out var globalNamespacesString); IEnumerable<GlobalImport>? globalImports = null; if (!string.IsNullOrEmpty(globalNamespacesString)) { globalImports = GlobalImport.Parse(globalNamespacesString.Split(';')); } VB.LanguageVersion langVersion = default; VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion); IReadOnlyDictionary<string, object>? preprocessorSymbols = null; if (pdbOptions.OptionToString(CompilationOptionNames.Define) is string defineString) { preprocessorSymbols = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(defineString, out var diagnostics); var diagnostic = diagnostics?.FirstOrDefault(x => x.IsUnsuppressedError); if (diagnostic is object) { throw new Exception(string.Format(RebuildResources.Cannot_create_compilation_options_0, diagnostic)); } } var parseOptions = VisualBasicParseOptions .Default .WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty()); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var isChecked = pdbOptions.OptionToBool(CompilationOptionNames.Checked) ?? true; var embedVBRuntime = pdbOptions.OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false; var rootNamespace = pdbOptions.OptionToString(CompilationOptionNames.RootNamespace); var compilationOptions = new VisualBasicCompilationOptions( pdbOptions.OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind) ?? OutputKind.DynamicallyLinkedLibrary, moduleName: assemblyFileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: "Script", globalImports: globalImports, rootNamespace: rootNamespace, optionStrict: pdbOptions.OptionToEnum<OptionStrict>(CompilationOptionNames.OptionStrict) ?? OptionStrict.Off, optionInfer: pdbOptions.OptionToBool(CompilationOptionNames.OptionInfer) ?? false, optionExplicit: pdbOptions.OptionToBool(CompilationOptionNames.OptionExplicit) ?? false, optionCompareText: pdbOptions.OptionToBool(CompilationOptionNames.OptionCompareText) ?? false, parseOptions: parseOptions, embedVbCoreRuntime: embedVBRuntime, optimizationLevel: optimizationLevel, checkOverflow: isChecked, cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, platform: GetPlatform(platform), generalDiagnosticOption: ReportDiagnostic.Default, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: RebuildSourceReferenceResolver.Instance, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, reportSuppressedDiagnostics: false, metadataImportOptions: MetadataImportOptions.Public); compilationOptions.DebugPlusMode = plus; return compilationOptions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Rebuild { public sealed class VisualBasicCompilationFactory : CompilationFactory { public new VisualBasicCompilationOptions CompilationOptions { get; } public new VisualBasicParseOptions ParseOptions => CompilationOptions.ParseOptions; protected override ParseOptions CommonParseOptions => ParseOptions; protected override CompilationOptions CommonCompilationOptions => CompilationOptions; private VisualBasicCompilationFactory( string assemblyFileName, CompilationOptionsReader optionsReader, VisualBasicCompilationOptions compilationOptions) : base(assemblyFileName, optionsReader) { CompilationOptions = compilationOptions; } internal static new VisualBasicCompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) { Debug.Assert(optionsReader.GetLanguageName() == LanguageNames.VisualBasic); var compilationOptions = CreateVisualBasicCompilationOptions(assemblyFileName, optionsReader); return new VisualBasicCompilationFactory(assemblyFileName, optionsReader, compilationOptions); } public override SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText) => VisualBasicSyntaxTree.ParseText(sourceText, ParseOptions, filePath); public override Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences) => VisualBasicCompilation.Create( Path.GetFileNameWithoutExtension(AssemblyFileName), syntaxTrees: syntaxTrees, references: metadataReferences, options: CompilationOptions); private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(string assemblyFileName, CompilationOptionsReader optionsReader) { var pdbOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); pdbOptions.TryGetUniqueOption(CompilationOptionNames.GlobalNamespaces, out var globalNamespacesString); IEnumerable<GlobalImport>? globalImports = null; if (!string.IsNullOrEmpty(globalNamespacesString)) { globalImports = GlobalImport.Parse(globalNamespacesString.Split(';')); } VB.LanguageVersion langVersion = default; VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion); IReadOnlyDictionary<string, object>? preprocessorSymbols = null; if (pdbOptions.OptionToString(CompilationOptionNames.Define) is string defineString) { preprocessorSymbols = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(defineString, out var diagnostics); var diagnostic = diagnostics?.FirstOrDefault(x => x.IsUnsuppressedError); if (diagnostic is object) { throw new Exception(string.Format(RebuildResources.Cannot_create_compilation_options_0, diagnostic)); } } var parseOptions = VisualBasicParseOptions .Default .WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty()); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var isChecked = pdbOptions.OptionToBool(CompilationOptionNames.Checked) ?? true; var embedVBRuntime = pdbOptions.OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false; var rootNamespace = pdbOptions.OptionToString(CompilationOptionNames.RootNamespace); var compilationOptions = new VisualBasicCompilationOptions( pdbOptions.OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind) ?? OutputKind.DynamicallyLinkedLibrary, moduleName: assemblyFileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: "Script", globalImports: globalImports, rootNamespace: rootNamespace, optionStrict: pdbOptions.OptionToEnum<OptionStrict>(CompilationOptionNames.OptionStrict) ?? OptionStrict.Off, optionInfer: pdbOptions.OptionToBool(CompilationOptionNames.OptionInfer) ?? false, optionExplicit: pdbOptions.OptionToBool(CompilationOptionNames.OptionExplicit) ?? false, optionCompareText: pdbOptions.OptionToBool(CompilationOptionNames.OptionCompareText) ?? false, parseOptions: parseOptions, embedVbCoreRuntime: embedVBRuntime, optimizationLevel: optimizationLevel, checkOverflow: isChecked, cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, platform: GetPlatform(platform), generalDiagnosticOption: ReportDiagnostic.Default, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: RebuildSourceReferenceResolver.Instance, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, reportSuppressedDiagnostics: false, metadataImportOptions: MetadataImportOptions.Public); compilationOptions.DebugPlusMode = plus; return compilationOptions; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedPropertySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/OverriddenOrHiddenMembersHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Encapsulates the MakeOverriddenOrHiddenMembers functionality for methods, properties (including indexers), /// and events. /// </summary> internal static class OverriddenOrHiddenMembersHelpers { internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this MethodSymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this PropertySymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this EventSymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } /// <summary> /// Walk up the type hierarchy from ContainingType and list members that this /// member either overrides (accessible members with the same signature, if this /// member is declared "override") or hides (accessible members with the same name /// but different kinds, plus members that would be in the overrides list if /// this member were not declared "override"). /// /// Members in the overridden list may be non-virtual or may have different /// accessibilities, types, accessors, etc. They are really candidates to be /// overridden. /// /// Members in the hidden list are definitely hidden. /// /// Members in the runtime overridden list are indistinguishable from the members /// in the overridden list from the point of view of the runtime (see /// FindOtherOverriddenMethodsInContainingType for details). /// </summary> /// <remarks> /// In the presence of non-C# types, the meaning of "same signature" is rather /// complicated. If this member isn't from source, then it refers to the runtime's /// notion of signature (i.e. including return type, custom modifiers, etc). /// If this member is from source, then the process is (conceptually) as follows. /// /// 1) Walk up the type hierarchy, recording all matching members with the same /// signature, ignoring custom modifiers and return type. Stop if a hidden /// member is encountered. /// 2) Apply the following "tie-breaker" rules until you have at most one member, /// a) Prefer members in more derived types. /// b) Prefer an exact custom modifier match (i.e. none, for a source member). /// c) Prefer fewer custom modifiers (values/positions don't matter, just count). /// d) Prefer earlier in GetMembers order (within the same type). /// 3) If a member remains, search its containing type for other members that /// have the same C# signature (overridden members) or runtime signature /// (runtime overridden members). /// /// In metadata, properties participate in overriding only through their accessors. /// That is, property/event accessors may implicitly or explicitly override other methods /// and a property/event can be considered to override another property/event if its accessors /// override those of the other property/event. /// This implementation (like Dev10) will not follow that approach. Instead, it is /// based on spec section 10.7.5, which treats properties as entities in their own /// right. If all property/event accessors have conventional names in metadata and nothing /// "unusual" is done with explicit overriding, this approach should produce the same /// results as an implementation based on accessor overriding. /// </remarks> private static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembersWorker(Symbol member) { Debug.Assert(member.Kind == SymbolKind.Method || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); if (!CanOverrideOrHide(member)) { return OverriddenOrHiddenMembersResult.Empty; } if (member.IsAccessor()) { // Accessors are handled specially - see MakePropertyAccessorOverriddenOrHiddenMembers for details. MethodSymbol accessor = member as MethodSymbol; Symbol associatedPropertyOrEvent = accessor.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null) { if (associatedPropertyOrEvent.Kind == SymbolKind.Property) { return MakePropertyAccessorOverriddenOrHiddenMembers(accessor, (PropertySymbol)associatedPropertyOrEvent); } else { Debug.Assert(associatedPropertyOrEvent.Kind == SymbolKind.Event); return MakeEventAccessorOverriddenOrHiddenMembers(accessor, (EventSymbol)associatedPropertyOrEvent); } } } Debug.Assert(!member.IsAccessor()); NamedTypeSymbol containingType = member.ContainingType; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about overriding or hiding. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // We believe that source and metadata behaviors agree for correct code, modulo accomodations for // runtime bugs (such as https://github.com/dotnet/roslyn/issues/45453) on older platforms. // In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. bool memberIsFromSomeCompilation = member.Dangerous_IsFromSomeCompilation; if (containingType.IsInterface) { return MakeInterfaceOverriddenOrHiddenMembers(member, memberIsFromSomeCompilation); } ArrayBuilder<Symbol> hiddenBuilder; ImmutableArray<Symbol> overriddenMembers; FindOverriddenOrHiddenMembers(member, containingType, memberIsFromSomeCompilation, out hiddenBuilder, out overriddenMembers); ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); } private static void FindOverriddenOrHiddenMembers(Symbol member, NamedTypeSymbol containingType, bool memberIsFromSomeCompilation, out ArrayBuilder<Symbol> hiddenBuilder, out ImmutableArray<Symbol> overriddenMembers) { Symbol bestMatch = null; hiddenBuilder = null; // A specific override exact match candidate, if one is known. This supports covariant returns, for which signature // matching is not sufficient. This member is treated as being as good as an exact match. Symbol knownOverriddenMember = member switch { MethodSymbol method => KnownOverriddenClassMethod(method), PEPropertySymbol { GetMethod: PEMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol overriddenProperty } } } => overriddenProperty, RetargetingPropertySymbol { GetMethod: RetargetingMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol overriddenProperty } } } => overriddenProperty, _ => null }; for (NamedTypeSymbol currType = containingType.BaseTypeNoUseSiteDiagnostics; (object)currType != null && (object)bestMatch == null && hiddenBuilder == null; currType = currType.BaseTypeNoUseSiteDiagnostics) { bool unused; FindOverriddenOrHiddenMembersInType( member, memberIsFromSomeCompilation, containingType, knownOverriddenMember, currType, out bestMatch, out unused, out hiddenBuilder); } // Based on bestMatch, find other methods that will be overridden, hidden, or runtime overridden // (in bestMatch.ContainingType). FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, bestMatch, out overriddenMembers, ref hiddenBuilder); } public static Symbol FindFirstHiddenMemberIfAny(Symbol member, bool memberIsFromSomeCompilation) { ArrayBuilder<Symbol> hiddenBuilder; FindOverriddenOrHiddenMembers(member, member.ContainingType, memberIsFromSomeCompilation, out hiddenBuilder, overriddenMembers: out _); Symbol result = hiddenBuilder?.FirstOrDefault(); hiddenBuilder?.Free(); return result; } /// <summary> /// Compute a candidate overridden method when a method knows what method it is intended to /// override. This makes a particular difference when covariant returns are used, in which /// case the signature matching rules would not compute the correct overridden method. /// </summary> private static MethodSymbol KnownOverriddenClassMethod(MethodSymbol method) => method switch { PEMethodSymbol m => m.ExplicitlyOverriddenClassMethod, RetargetingMethodSymbol m => m.ExplicitlyOverriddenClassMethod, _ => null }; /// <summary> /// In the CLI, accessors are just regular methods and their overriding/hiding rules are the same as for /// regular methods. In C#, however, accessors are intimately connected with their corresponding properties. /// Rather than walking up the type hierarchy from the containing type of this accessor, looking for members /// with the same name, MakePropertyAccessorOverriddenOrHiddenMembers delegates to the associated property. /// For an accessor to hide a member, the hidden member must be a corresponding accessor on a property hidden /// by the associated property. For an accessor to override a member, the overridden member must be a /// corresponding accessor on a property (directly or indirectly) overridden by the associated property. /// /// Example 1: /// /// public class A { public virtual int P { get; set; } } /// public class B : A { public override int P { get { return 1; } } } //get only /// public class C : B { public override int P { set { } } } // set only /// /// C.P.set overrides A.P.set because C.P.set is the setter of C.P, which overrides B.P, /// which overrides A.P, which has A.P.set as a setter. /// /// Example 2: /// /// public class A { public virtual int P { get; set; } } /// public class B : A { public new virtual int P { get { return 1; } } } //get only /// public class C : B { public override int P { set { } } } // set only /// /// C.P.set does not override any method because C.P overrides B.P, which has no setter /// and does not override a property. /// </summary> /// <param name="accessor">This accessor.</param> /// <param name="associatedProperty">The property associated with this accessor.</param> /// <returns>Members overridden or hidden by this accessor.</returns> /// <remarks> /// This method is intended to return values consistent with the definition of C#, which /// may differ from the actual meaning at runtime. /// /// Note: we don't need a different path for interfaces - Property.OverriddenOrHiddenMembers handles that. /// </remarks> private static OverriddenOrHiddenMembersResult MakePropertyAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, PropertySymbol associatedProperty) { Debug.Assert(accessor.IsAccessor()); Debug.Assert((object)associatedProperty != null); bool accessorIsGetter = accessor.MethodKind == MethodKind.PropertyGet; MethodSymbol overriddenAccessor = null; ArrayBuilder<Symbol> hiddenBuilder = null; OverriddenOrHiddenMembersResult hiddenOrOverriddenByProperty = associatedProperty.OverriddenOrHiddenMembers; foreach (Symbol hiddenByProperty in hiddenOrOverriddenByProperty.HiddenMembers) { if (hiddenByProperty.Kind == SymbolKind.Property) { // If we're looking at the associated property of this method (vs a property // it overrides), then record the corresponding accessor (if any) as hidden. PropertySymbol propertyHiddenByProperty = (PropertySymbol)hiddenByProperty; MethodSymbol correspondingAccessor = accessorIsGetter ? propertyHiddenByProperty.GetMethod : propertyHiddenByProperty.SetMethod; if ((object)correspondingAccessor != null) { AccessOrGetInstance(ref hiddenBuilder).Add(correspondingAccessor); } } } if (hiddenOrOverriddenByProperty.OverriddenMembers.Any()) { // CONSIDER: Do something more sensible if there are multiple overridden members? Already an error case. PropertySymbol propertyOverriddenByProperty = (PropertySymbol)hiddenOrOverriddenByProperty.OverriddenMembers[0]; MethodSymbol correspondingAccessor = accessorIsGetter ? propertyOverriddenByProperty.GetOwnOrInheritedGetMethod() : propertyOverriddenByProperty.GetOwnOrInheritedSetMethod(); if ((object)correspondingAccessor != null) { overriddenAccessor = correspondingAccessor; } } // There's a detailed comment in MakeOverriddenOrHiddenMembersWorker(Symbol) concerning why this predicate is appropriate. bool accessorIsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; ImmutableArray<Symbol> overriddenAccessors = ImmutableArray<Symbol>.Empty; if ((object)overriddenAccessor != null && IsOverriddenSymbolAccessible(overriddenAccessor, accessor.ContainingType) && isAccessorOverride(accessor, overriddenAccessor)) { FindRelatedMembers( accessor.IsOverride, accessorIsFromSomeCompilation, accessor.Kind, overriddenAccessor, out overriddenAccessors, ref hiddenBuilder); } ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenAccessors, hiddenMembers); bool isAccessorOverride(MethodSymbol accessor, MethodSymbol overriddenAccessor) { if (accessorIsFromSomeCompilation) { return MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(accessor, overriddenAccessor); //NB: custom comparer } if (overriddenAccessor.Equals(KnownOverriddenClassMethod(accessor), TypeCompareKind.AllIgnoreOptions)) { return true; } return MemberSignatureComparer.RuntimeSignatureComparer.Equals(accessor, overriddenAccessor); } } /// <summary> /// In the CLI, accessors are just regular methods and their overriding/hiding rules are the same as for /// regular methods. In C#, however, accessors are intimately connected with their corresponding events. /// Rather than walking up the type hierarchy from the containing type of this accessor, looking for members /// with the same name, MakeEventAccessorOverriddenOrHiddenMembers delegates to the associated event. /// For an accessor to hide a member, the hidden member must be a corresponding accessor on a event hidden /// by the associated event. For an accessor to override a member, the overridden member must be a /// corresponding accessor on a event (directly or indirectly) overridden by the associated event. /// </summary> /// <param name="accessor">This accessor.</param> /// <param name="associatedEvent">The event associated with this accessor.</param> /// <returns>Members overridden or hidden by this accessor.</returns> /// <remarks> /// This method is intended to return values consistent with the definition of C#, which /// may differ from the actual meaning at runtime. /// /// Note: we don't need a different path for interfaces - Event.OverriddenOrHiddenMembers handles that. /// /// CONSIDER: It is an error for an event to have only one accessor. Currently, we mimic the behavior for /// properties, for consistency, but an alternative approach would be to say that nothing is overridden. /// /// CONSIDER: is there a way to share code with MakePropertyAccessorOverriddenOrHiddenMembers? /// </remarks> private static OverriddenOrHiddenMembersResult MakeEventAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, EventSymbol associatedEvent) { Debug.Assert(accessor.IsAccessor()); Debug.Assert((object)associatedEvent != null); bool accessorIsAdder = accessor.MethodKind == MethodKind.EventAdd; MethodSymbol overriddenAccessor = null; ArrayBuilder<Symbol> hiddenBuilder = null; OverriddenOrHiddenMembersResult hiddenOrOverriddenByEvent = associatedEvent.OverriddenOrHiddenMembers; foreach (Symbol hiddenByEvent in hiddenOrOverriddenByEvent.HiddenMembers) { if (hiddenByEvent.Kind == SymbolKind.Event) { // If we're looking at the associated event of this method (vs a event // it overrides), then record the corresponding accessor (if any) as hidden. EventSymbol eventHiddenByEvent = (EventSymbol)hiddenByEvent; MethodSymbol correspondingAccessor = accessorIsAdder ? eventHiddenByEvent.AddMethod : eventHiddenByEvent.RemoveMethod; if ((object)correspondingAccessor != null) { AccessOrGetInstance(ref hiddenBuilder).Add(correspondingAccessor); } } } if (hiddenOrOverriddenByEvent.OverriddenMembers.Any()) { // CONSIDER: Do something more sensible if there are multiple overridden members? Already an error case. EventSymbol eventOverriddenByEvent = (EventSymbol)hiddenOrOverriddenByEvent.OverriddenMembers[0]; MethodSymbol correspondingAccessor = eventOverriddenByEvent.GetOwnOrInheritedAccessor(accessorIsAdder); if ((object)correspondingAccessor != null) { overriddenAccessor = correspondingAccessor; } } // There's a detailed comment in MakeOverriddenOrHiddenMembersWorker(Symbol) concerning why this predicate is appropriate. bool accessorIsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; ImmutableArray<Symbol> overriddenAccessors = ImmutableArray<Symbol>.Empty; if ((object)overriddenAccessor != null && IsOverriddenSymbolAccessible(overriddenAccessor, accessor.ContainingType) && (accessorIsFromSomeCompilation ? MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(accessor, overriddenAccessor) //NB: custom comparer : MemberSignatureComparer.RuntimeSignatureComparer.Equals(accessor, overriddenAccessor))) { FindRelatedMembers( accessor.IsOverride, accessorIsFromSomeCompilation, accessor.Kind, overriddenAccessor, out overriddenAccessors, ref hiddenBuilder); } ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenAccessors, hiddenMembers); } /// <summary> /// There are two key reasons why interface overriding/hiding is different from class overriding/hiding: /// 1) interface members never override other members; and /// 2) interfaces can extend multiple interfaces. /// The first difference doesn't require any special handling - as long as the members have IsOverride=false, /// the code for class overriding/hiding does the right thing. /// The second difference is more problematic. For one thing, an interface member can hide a different member in /// each base interface. We only report the first one, but we need to expose all of them in the API. More importantly, /// multiple inheritance raises the possibility of diamond inheritance. Spec section 13.2.5, Interface member access, /// says: "The intuitive rule for hiding in multiple-inheritance interfaces is simply this: If a member is hidden in any /// access path, it is hidden in all access paths." For example, consider the following interfaces: /// /// interface I0 { void M(); } /// interface I1 : I0 { void M(); } /// interface I2 : I0, I1 { void M(); } /// /// I2.M does not hide I0.M, because it is already hidden by I1.M. To make this work, we need to traverse the graph /// of ancestor interfaces in topological order and flag ones later in the enumeration that are hidden along some path. /// </summary> /// <remarks> /// See SymbolPreparer::checkIfaceHiding. /// </remarks> internal static OverriddenOrHiddenMembersResult MakeInterfaceOverriddenOrHiddenMembers(Symbol member, bool memberIsFromSomeCompilation) { Debug.Assert(!member.IsAccessor()); NamedTypeSymbol containingType = member.ContainingType; Debug.Assert(containingType.IsInterfaceType()); PooledHashSet<NamedTypeSymbol> membersOfOtherKindsHidden = PooledHashSet<NamedTypeSymbol>.GetInstance(); PooledHashSet<NamedTypeSymbol> allMembersHidden = PooledHashSet<NamedTypeSymbol>.GetInstance(); // Implies membersOfOtherKindsHidden. ArrayBuilder<Symbol> hiddenBuilder = null; foreach (NamedTypeSymbol currType in containingType.AllInterfacesNoUseSiteDiagnostics) // NB: topologically sorted { if (allMembersHidden.Contains(currType)) { continue; } Symbol currTypeBestMatch; bool currTypeHasSameKindNonMatch; ArrayBuilder<Symbol> currTypeHiddenBuilder; FindOverriddenOrHiddenMembersInType( member, memberIsFromSomeCompilation, containingType, knownOverriddenMember: null, currType, out currTypeBestMatch, out currTypeHasSameKindNonMatch, out currTypeHiddenBuilder); bool haveBestMatch = (object)currTypeBestMatch != null; if (haveBestMatch) { // If our base interface contains a matching member of the same kind, // then we don't need to look any further up this subtree. foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { allMembersHidden.Add(hidden); } AccessOrGetInstance(ref hiddenBuilder).Add(currTypeBestMatch); } if (currTypeHiddenBuilder != null) { // If our base interface contains a matching member of a different kind, then // it will hide all members that aren't of that kind further up the chain. // As a result, nothing of our kind will be visible and we can stop looking. if (!membersOfOtherKindsHidden.Contains(currType)) { if (!haveBestMatch) { foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { allMembersHidden.Add(hidden); } } AccessOrGetInstance(ref hiddenBuilder).AddRange(currTypeHiddenBuilder); } currTypeHiddenBuilder.Free(); } else if (currTypeHasSameKindNonMatch && !haveBestMatch) { // If our base interface contains a (non-matching) member of the same kind, then // it will hide all members that aren't of that kind further up the chain. foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { membersOfOtherKindsHidden.Add(hidden); } } } membersOfOtherKindsHidden.Free(); allMembersHidden.Free(); // Based on bestMatch, find other methods that will be overridden, hidden, or runtime overridden // (in bestMatch.ContainingType). ImmutableArray<Symbol> overriddenMembers = ImmutableArray<Symbol>.Empty; if (hiddenBuilder != null) { ArrayBuilder<Symbol> hiddenAndRelatedBuilder = null; foreach (Symbol hidden in hiddenBuilder) { FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, hidden, out overriddenMembers, ref hiddenAndRelatedBuilder); Debug.Assert(overriddenMembers.Length == 0); } hiddenBuilder.Free(); hiddenBuilder = hiddenAndRelatedBuilder; } Debug.Assert(overriddenMembers.IsEmpty); ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); } /// <summary> /// Look for overridden or hidden members in a specific type. /// </summary> /// <param name="member">Member that is hiding or overriding.</param> /// <param name="memberIsFromSomeCompilation">True if member is from the current compilation.</param> /// <param name="memberContainingType">The type that contains member (member.ContainingType).</param> /// <param name="knownOverriddenMember">The known overridden member (e.g. in the presence of a metadata methodimpl).</param> /// <param name="currType">The type to search.</param> /// <param name="currTypeBestMatch"> /// A member with the same signature if currTypeHasExactMatch is true, /// a member with (a minimal number of) different custom modifiers if there is one, /// and null otherwise.</param> /// <param name="currTypeHasSameKindNonMatch">True if there's a member with the same name and kind that is not a match.</param> /// <param name="hiddenBuilder">Hidden members (same name, different kind) will be added to this builder.</param> /// <remarks> /// There is some similarity between this member and TypeSymbol.FindPotentialImplicitImplementationMemberDeclaredInType. /// When making changes to this member, think about whether or not they should also be applied in TypeSymbol. /// /// In incorrect or imported code, it is possible that both currTypeBestMatch and hiddenBuilder will be populated. /// </remarks> private static void FindOverriddenOrHiddenMembersInType( Symbol member, bool memberIsFromSomeCompilation, NamedTypeSymbol memberContainingType, Symbol knownOverriddenMember, NamedTypeSymbol currType, out Symbol currTypeBestMatch, out bool currTypeHasSameKindNonMatch, out ArrayBuilder<Symbol> hiddenBuilder) { Debug.Assert(!member.IsAccessor()); currTypeBestMatch = null; currTypeHasSameKindNonMatch = false; hiddenBuilder = null; bool currTypeHasExactMatch = false; int minCustomModifierCount = int.MaxValue; IEqualityComparer<Symbol> exactMatchComparer = memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpCustomModifierOverrideComparer : MemberSignatureComparer.RuntimePlusRefOutSignatureComparer; IEqualityComparer<Symbol> fallbackComparer = memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpOverrideComparer : MemberSignatureComparer.RuntimeSignatureComparer; SymbolKind memberKind = member.Kind; int memberArity = member.GetMemberArity(); foreach (Symbol otherMember in currType.GetMembers(member.Name)) { if (!IsOverriddenSymbolAccessible(otherMember, memberContainingType)) { //do nothing } else if (otherMember.IsAccessor() && !((MethodSymbol)otherMember).IsIndexedPropertyAccessor()) { //Indexed property accessors can be overridden or hidden by non-accessors. //do nothing - no interaction between accessors and non-accessors } else if (otherMember.Kind != memberKind) { // NOTE: generic methods can hide things with arity 0. // From CSemanticChecker::FindSymHiddenByMethPropAgg int otherMemberArity = otherMember.GetMemberArity(); if (otherMemberArity == memberArity || (memberKind == SymbolKind.Method && otherMemberArity == 0)) { AddHiddenMemberIfApplicable(ref hiddenBuilder, memberKind, otherMember); } } else if (!currTypeHasExactMatch) { switch (memberKind) { case SymbolKind.Field: currTypeHasExactMatch = true; currTypeBestMatch = otherMember; break; case SymbolKind.NamedType: if (otherMember.GetMemberArity() == memberArity) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } break; default: if (otherMember.Equals(knownOverriddenMember, TypeCompareKind.AllIgnoreOptions)) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } // We do not perform signature matching in the presence of a methodimpl else if (knownOverriddenMember == null) { if (exactMatchComparer.Equals(member, otherMember)) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } else if (fallbackComparer.Equals(member, otherMember)) { // If this method is from source, we'll also consider methods that match // without regard to custom modifiers. If there's more than one, we'll // choose the one with the fewest custom modifiers. int methodCustomModifierCount = CustomModifierCount(otherMember); if (methodCustomModifierCount < minCustomModifierCount) { Debug.Assert(memberIsFromSomeCompilation || minCustomModifierCount == int.MaxValue, "Metadata members require exact custom modifier matches."); minCustomModifierCount = methodCustomModifierCount; currTypeBestMatch = otherMember; } } else { currTypeHasSameKindNonMatch = true; } } break; } } } switch (memberKind) { case SymbolKind.Field: case SymbolKind.NamedType: break; default: // If the member is from metadata, then even a fallback match is an exact match. // We just declined to set the flag at the time in case there was a "better" exact match. // Having said that, there's no reason to update the flag, since no-one will consume it. // if (!memberIsFromSomeCompilation && ((object)currTypeBestMatch != null)) currTypeHasExactMatch = true; // There's a special case where we have to go back and fix up our best match. // If member is from source, then it has no custom modifiers (at least, // until it copies them from the member it overrides, which we're trying to // compute now). Therefore, an exact match will be one that has no custom // modifiers in/on its parameters. The best match may, however, have custom // modifiers in/on its (return) type, since that wasn't considered during the // signature comparison. If that is the case, then we need to make sure that // there isn't another inexact match (i.e. same signature ignoring custom // modifiers) with fewer custom modifiers. // NOTE: If member is constructed, then it has already inherited custom modifiers // from the underlying member and this cleanup is unnecessary. That's why we're // checking member.IsDefinition in addition to memberIsFromSomeCompilation. if (currTypeHasExactMatch && memberIsFromSomeCompilation && member.IsDefinition && TypeOrReturnTypeHasCustomModifiers(currTypeBestMatch)) { #if DEBUG // If there were custom modifiers on the parameters, then the match wouldn't have been // exact and so we would already have applied the custom modifier count as a tie-breaker. foreach (ParameterSymbol param in currTypeBestMatch.GetParameters()) { Debug.Assert(!(param.TypeWithAnnotations.CustomModifiers.Any() || param.RefCustomModifiers.Any())); Debug.Assert(!param.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false)); } #endif Symbol minCustomModifierMatch = currTypeBestMatch; foreach (Symbol otherMember in currType.GetMembers(member.Name)) { if (otherMember.Kind == currTypeBestMatch.Kind && !ReferenceEquals(otherMember, currTypeBestMatch)) { if (MemberSignatureComparer.CSharpOverrideComparer.Equals(otherMember, currTypeBestMatch)) { int customModifierCount = CustomModifierCount(otherMember); if (customModifierCount < minCustomModifierCount) { minCustomModifierCount = customModifierCount; minCustomModifierMatch = otherMember; } } } } currTypeBestMatch = minCustomModifierMatch; } break; } } /// <summary> /// If representative member is non-null and is contained in a constructed type, then find /// other members in the same type with the same signature. If this is an override member, /// add them to the overridden and runtime overridden lists. Otherwise, add them to the /// hidden list. /// </summary> private static void FindRelatedMembers( bool isOverride, bool overridingMemberIsFromSomeCompilation, SymbolKind overridingMemberKind, Symbol representativeMember, out ImmutableArray<Symbol> overriddenMembers, ref ArrayBuilder<Symbol> hiddenBuilder) { overriddenMembers = ImmutableArray<Symbol>.Empty; if ((object)representativeMember != null) { bool needToSearchForRelated = representativeMember.Kind != SymbolKind.Field && representativeMember.Kind != SymbolKind.NamedType && (!representativeMember.ContainingType.IsDefinition || representativeMember.IsIndexer()); if (isOverride) { if (needToSearchForRelated) { ArrayBuilder<Symbol> overriddenBuilder = ArrayBuilder<Symbol>.GetInstance(); overriddenBuilder.Add(representativeMember); FindOtherOverriddenMethodsInContainingType(representativeMember, overridingMemberIsFromSomeCompilation, overriddenBuilder); overriddenMembers = overriddenBuilder.ToImmutableAndFree(); } else { overriddenMembers = ImmutableArray.Create<Symbol>(representativeMember); } } else { AddHiddenMemberIfApplicable(ref hiddenBuilder, overridingMemberKind, representativeMember); if (needToSearchForRelated) { FindOtherHiddenMembersInContainingType(overridingMemberKind, representativeMember, ref hiddenBuilder); } } } } /// <summary> /// Some kinds of methods are not considered to be hideable by certain kinds of members. /// Specifically, methods, properties, and types cannot hide constructors, destructors, /// operators, conversions, or accessors. /// </summary> private static void AddHiddenMemberIfApplicable(ref ArrayBuilder<Symbol> hiddenBuilder, SymbolKind hidingMemberKind, Symbol hiddenMember) { Debug.Assert((object)hiddenMember != null); if (hiddenMember.Kind != SymbolKind.Method || ((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(hidingMemberKind)) { AccessOrGetInstance(ref hiddenBuilder).Add(hiddenMember); } } private static ArrayBuilder<T> AccessOrGetInstance<T>(ref ArrayBuilder<T> builder) { if (builder == null) { builder = ArrayBuilder<T>.GetInstance(); } return builder; } /// <summary> /// Having found the best member to override, we want to find members with the same signature on the /// best member's containing type. /// </summary> /// <param name="representativeMember"> /// The member that we consider to be overridden (may have different custom modifiers from the overriding member). /// Assumed to already be in the overridden and runtime overridden lists. /// </param> /// <param name="overridingMemberIsFromSomeCompilation"> /// If the best match was based on the custom modifier count, rather than the custom modifiers themselves /// (because the overriding member is in the current compilation), then we should use the count when determining /// whether the override is ambiguous. /// </param> /// <param name="overriddenBuilder"> /// If the declaring type is constructed, it's possible that two (or more) members have the same signature /// (including custom modifiers). Return a list of such members so that we can report the ambiguity. /// </param> private static void FindOtherOverriddenMethodsInContainingType(Symbol representativeMember, bool overridingMemberIsFromSomeCompilation, ArrayBuilder<Symbol> overriddenBuilder) { Debug.Assert((object)representativeMember != null); Debug.Assert(representativeMember.Kind == SymbolKind.Property || !representativeMember.ContainingType.IsDefinition); int representativeCustomModifierCount = -1; foreach (Symbol otherMember in representativeMember.ContainingType.GetMembers(representativeMember.Name)) { if (otherMember.Kind == representativeMember.Kind) { if (otherMember != representativeMember) { // NOTE: If the overriding member is from source, then we compared *counts* of custom modifiers, rather // than actually comparing custom modifiers. Hence, we should do the same thing when looking for // ambiguous overrides. if (overridingMemberIsFromSomeCompilation) { if (representativeCustomModifierCount < 0) { representativeCustomModifierCount = representativeMember.CustomModifierCount(); } if (MemberSignatureComparer.CSharpOverrideComparer.Equals(otherMember, representativeMember) && otherMember.CustomModifierCount() == representativeCustomModifierCount) { overriddenBuilder.Add(otherMember); } } else { if (MemberSignatureComparer.CSharpCustomModifierOverrideComparer.Equals(otherMember, representativeMember)) { overriddenBuilder.Add(otherMember); } } } } } } /// <summary> /// Having found that we are hiding a method with exactly the same signature /// (including custom modifiers), we want to find methods with the same signature /// on the declaring type because they will also be hidden. /// (If the declaring type is constructed, it's possible that two or more /// methods have the same signature (including custom modifiers).) /// (If the representative member is an indexer, it's possible that two or more /// properties have the same signature (including custom modifiers, even in a /// non-generic type). /// </summary> /// <param name="hidingMemberKind"> /// This kind of the hiding member. /// </param> /// <param name="representativeMember"> /// The member that we consider to be hidden (must have exactly the same custom modifiers as the hiding member). /// Assumed to already be in hiddenBuilder. /// </param> /// <param name="hiddenBuilder"> /// Will have all other members with the same signature (including custom modifiers) as /// representativeMember added. /// </param> private static void FindOtherHiddenMembersInContainingType(SymbolKind hidingMemberKind, Symbol representativeMember, ref ArrayBuilder<Symbol> hiddenBuilder) { Debug.Assert((object)representativeMember != null); Debug.Assert(representativeMember.Kind != SymbolKind.Field); Debug.Assert(representativeMember.Kind != SymbolKind.NamedType); Debug.Assert(representativeMember.Kind == SymbolKind.Property || !representativeMember.ContainingType.IsDefinition); IEqualityComparer<Symbol> comparer = MemberSignatureComparer.CSharpCustomModifierOverrideComparer; foreach (Symbol otherMember in representativeMember.ContainingType.GetMembers(representativeMember.Name)) { if (otherMember.Kind == representativeMember.Kind) { if (otherMember != representativeMember && comparer.Equals(otherMember, representativeMember)) { AddHiddenMemberIfApplicable(ref hiddenBuilder, hidingMemberKind, otherMember); } } } } private static bool CanOverrideOrHide(Symbol member) { switch (member.Kind) { case SymbolKind.Property: case SymbolKind.Event: // Explicit interface impls don't override or hide. return !member.IsExplicitInterfaceImplementation(); case SymbolKind.Method: MethodSymbol methodSymbol = (MethodSymbol)member; return MethodSymbol.CanOverrideOrHide(methodSymbol.MethodKind) && ReferenceEquals(methodSymbol, methodSymbol.ConstructedFrom); default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static bool TypeOrReturnTypeHasCustomModifiers(Symbol member) { switch (member.Kind) { case SymbolKind.Method: MethodSymbol method = (MethodSymbol)member; var methodReturnType = method.ReturnTypeWithAnnotations; return methodReturnType.CustomModifiers.Any() || method.RefCustomModifiers.Any() || methodReturnType.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); case SymbolKind.Property: PropertySymbol property = (PropertySymbol)member; var propertyType = property.TypeWithAnnotations; return propertyType.CustomModifiers.Any() || property.RefCustomModifiers.Any() || propertyType.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); case SymbolKind.Event: EventSymbol @event = (EventSymbol)member; return @event.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); //can't have custom modifiers on (vs in) type default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static int CustomModifierCount(Symbol member) { switch (member.Kind) { case SymbolKind.Method: MethodSymbol method = (MethodSymbol)member; return method.CustomModifierCount(); case SymbolKind.Property: PropertySymbol property = (PropertySymbol)member; return property.CustomModifierCount(); case SymbolKind.Event: EventSymbol @event = (EventSymbol)member; return @event.Type.CustomModifierCount(); default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } /// <summary> /// Determine if this method requires a methodimpl table entry to inform the runtime of the override relationship. /// </summary> /// <param name="warnAmbiguous">True if we should produce an ambiguity warning per https://github.com/dotnet/roslyn/issues/45453 .</param> internal static bool RequiresExplicitOverride(this MethodSymbol method, out bool warnAmbiguous) { warnAmbiguous = false; if (!method.IsOverride) return false; MethodSymbol csharpOverriddenMethod = method.OverriddenMethod; if (csharpOverriddenMethod is null) return false; MethodSymbol runtimeOverriddenMethod = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out bool wasAmbiguous); if (csharpOverriddenMethod == runtimeOverriddenMethod && !wasAmbiguous) return false; // See https://github.com/dotnet/roslyn/issues/45453. No need to warn when the runtime // supports covariant returns because any methodimpl we produce to identify the specific // overridden method is unambiguously understood by the runtime. if (method.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) return true; // If the method was declared as a covariant return, there will be a compile-time error since the runtime // does not support covariant returns. In this case we do not warn about runtime ambiguity and pretend that // we can use a methodimpl (even though it is of a form not supported by the runtime and would result in a // loader error) so that the symbol APIs produce the most useful result. if (!method.ReturnType.Equals(csharpOverriddenMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) return true; // Due to https://github.com/dotnet/runtime/issues/38119 the methodimpl would // appear to the runtime to be ambiguous in some cases. bool methodimplWouldBeAmbiguous = csharpOverriddenMethod.MethodHasRuntimeCollision(); if (!methodimplWouldBeAmbiguous) return true; Debug.Assert(runtimeOverriddenMethod is { }); // We produce the warning when a methodimpl would be required but would be ambiguous to the runtime. // However, if there was a duplicate definition for the runtime signature of the overridden // method where it was originally declared, that would have been an error. In that case we suppress // the warning as a cascaded diagnostic. bool originalOverriddenMethodWasAmbiguous = csharpOverriddenMethod.IsDefinition || csharpOverriddenMethod.OriginalDefinition.MethodHasRuntimeCollision(); warnAmbiguous = !originalOverriddenMethodWasAmbiguous; bool overriddenMethodContainedInSameTypeAsRuntimeOverriddenMethod = csharpOverriddenMethod.ContainingType.Equals(runtimeOverriddenMethod.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); // If the overridden method is on a different (e.g. base) type compared to the runtime overridden // method, then the runtime overridden method could not possibly resolve correctly to the overridden method. // In this case we might as well produce a methodimpl. At least it has a chance of being correctly resolved // by the runtime, where the runtime resolution without the methodimpl would definitely be wrong. if (!overriddenMethodContainedInSameTypeAsRuntimeOverriddenMethod) return true; // This is the historical test, preserved since the days of the native compiler in case it turns out to affect compatibility. // However, this test cannot be true in a program free of errors. return csharpOverriddenMethod != runtimeOverriddenMethod && method.IsAccessor() != runtimeOverriddenMethod.IsAccessor(); } internal static bool MethodHasRuntimeCollision(this MethodSymbol method) { foreach (Symbol otherMethod in method.ContainingType.GetMembers(method.Name)) { if (otherMethod != method && MemberSignatureComparer.RuntimeSignatureComparer.Equals(otherMethod, method)) { return true; } } return false; } /// <summary> /// Given a method, find the first method that it overrides from the perspective of the CLI. /// Key differences from C#: non-virtual methods are ignored, the RuntimeSignatureComparer /// is used (i.e. consider return types, ignore ref/out distinction). Sets <paramref name="wasAmbiguous"/> /// to true if more than one method is overridden by CLI rules. /// </summary> /// <remarks> /// WARN: Must not check method.MethodKind - PEMethodSymbol.ComputeMethodKind uses this method. /// NOTE: Does not check whether the given method will be marked "newslot" in metadata (as /// "newslot" is used for covariant method overrides). /// </remarks> internal static MethodSymbol GetFirstRuntimeOverriddenMethodIgnoringNewSlot(this MethodSymbol method, out bool wasAmbiguous) { // WARN: If the method may override a source method and declaration diagnostics have yet to // be computed, then it is important for us to pass ignoreInterfaceImplementationChanges: true // (see MethodSymbol.IsMetadataVirtual for details). // Since we are only concerned with overrides (of class methods), interface implementations can be ignored. const bool ignoreInterfaceImplementationChanges = true; wasAmbiguous = false; if (!method.IsMetadataVirtual(ignoreInterfaceImplementationChanges) || method.IsStatic) { return null; } NamedTypeSymbol containingType = method.ContainingType; for (NamedTypeSymbol currType = containingType.BaseTypeNoUseSiteDiagnostics; !ReferenceEquals(currType, null); currType = currType.BaseTypeNoUseSiteDiagnostics) { MethodSymbol candidate = null; foreach (Symbol otherMember in currType.GetMembers(method.Name)) { if (otherMember.Kind == SymbolKind.Method && IsOverriddenSymbolAccessible(otherMember, containingType) && MemberSignatureComparer.RuntimeSignatureComparer.Equals(method, otherMember)) { MethodSymbol overridden = (MethodSymbol)otherMember; // NOTE: The runtime doesn't consider non-virtual methods during override resolution. if (overridden.IsMetadataVirtual(ignoreInterfaceImplementationChanges)) { if (candidate is { }) { // found more than one possible override in this type wasAmbiguous = true; return candidate; } candidate = overridden; } } } if (candidate is { }) { return candidate; } } return null; } /// <remarks> /// Note that the access check is done using the original definitions. This is because we want to avoid /// reductions in accessibility that result from type argument substitution (e.g. if an inaccessible type /// has been passed as a type argument). /// See DevDiv #11967 for an example. /// </remarks> private static bool IsOverriddenSymbolAccessible(Symbol overridden, NamedTypeSymbol overridingContainingType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return AccessCheck.IsSymbolAccessible(overridden.OriginalDefinition, overridingContainingType.OriginalDefinition, ref discardedUseSiteInfo); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Encapsulates the MakeOverriddenOrHiddenMembers functionality for methods, properties (including indexers), /// and events. /// </summary> internal static class OverriddenOrHiddenMembersHelpers { internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this MethodSymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this PropertySymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this EventSymbol member) { return MakeOverriddenOrHiddenMembersWorker(member); } /// <summary> /// Walk up the type hierarchy from ContainingType and list members that this /// member either overrides (accessible members with the same signature, if this /// member is declared "override") or hides (accessible members with the same name /// but different kinds, plus members that would be in the overrides list if /// this member were not declared "override"). /// /// Members in the overridden list may be non-virtual or may have different /// accessibilities, types, accessors, etc. They are really candidates to be /// overridden. /// /// Members in the hidden list are definitely hidden. /// /// Members in the runtime overridden list are indistinguishable from the members /// in the overridden list from the point of view of the runtime (see /// FindOtherOverriddenMethodsInContainingType for details). /// </summary> /// <remarks> /// In the presence of non-C# types, the meaning of "same signature" is rather /// complicated. If this member isn't from source, then it refers to the runtime's /// notion of signature (i.e. including return type, custom modifiers, etc). /// If this member is from source, then the process is (conceptually) as follows. /// /// 1) Walk up the type hierarchy, recording all matching members with the same /// signature, ignoring custom modifiers and return type. Stop if a hidden /// member is encountered. /// 2) Apply the following "tie-breaker" rules until you have at most one member, /// a) Prefer members in more derived types. /// b) Prefer an exact custom modifier match (i.e. none, for a source member). /// c) Prefer fewer custom modifiers (values/positions don't matter, just count). /// d) Prefer earlier in GetMembers order (within the same type). /// 3) If a member remains, search its containing type for other members that /// have the same C# signature (overridden members) or runtime signature /// (runtime overridden members). /// /// In metadata, properties participate in overriding only through their accessors. /// That is, property/event accessors may implicitly or explicitly override other methods /// and a property/event can be considered to override another property/event if its accessors /// override those of the other property/event. /// This implementation (like Dev10) will not follow that approach. Instead, it is /// based on spec section 10.7.5, which treats properties as entities in their own /// right. If all property/event accessors have conventional names in metadata and nothing /// "unusual" is done with explicit overriding, this approach should produce the same /// results as an implementation based on accessor overriding. /// </remarks> private static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembersWorker(Symbol member) { Debug.Assert(member.Kind == SymbolKind.Method || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); if (!CanOverrideOrHide(member)) { return OverriddenOrHiddenMembersResult.Empty; } if (member.IsAccessor()) { // Accessors are handled specially - see MakePropertyAccessorOverriddenOrHiddenMembers for details. MethodSymbol accessor = member as MethodSymbol; Symbol associatedPropertyOrEvent = accessor.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null) { if (associatedPropertyOrEvent.Kind == SymbolKind.Property) { return MakePropertyAccessorOverriddenOrHiddenMembers(accessor, (PropertySymbol)associatedPropertyOrEvent); } else { Debug.Assert(associatedPropertyOrEvent.Kind == SymbolKind.Event); return MakeEventAccessorOverriddenOrHiddenMembers(accessor, (EventSymbol)associatedPropertyOrEvent); } } } Debug.Assert(!member.IsAccessor()); NamedTypeSymbol containingType = member.ContainingType; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about overriding or hiding. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // We believe that source and metadata behaviors agree for correct code, modulo accomodations for // runtime bugs (such as https://github.com/dotnet/roslyn/issues/45453) on older platforms. // In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. bool memberIsFromSomeCompilation = member.Dangerous_IsFromSomeCompilation; if (containingType.IsInterface) { return MakeInterfaceOverriddenOrHiddenMembers(member, memberIsFromSomeCompilation); } ArrayBuilder<Symbol> hiddenBuilder; ImmutableArray<Symbol> overriddenMembers; FindOverriddenOrHiddenMembers(member, containingType, memberIsFromSomeCompilation, out hiddenBuilder, out overriddenMembers); ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); } private static void FindOverriddenOrHiddenMembers(Symbol member, NamedTypeSymbol containingType, bool memberIsFromSomeCompilation, out ArrayBuilder<Symbol> hiddenBuilder, out ImmutableArray<Symbol> overriddenMembers) { Symbol bestMatch = null; hiddenBuilder = null; // A specific override exact match candidate, if one is known. This supports covariant returns, for which signature // matching is not sufficient. This member is treated as being as good as an exact match. Symbol knownOverriddenMember = member switch { MethodSymbol method => KnownOverriddenClassMethod(method), PEPropertySymbol { GetMethod: PEMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol overriddenProperty } } } => overriddenProperty, RetargetingPropertySymbol { GetMethod: RetargetingMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol overriddenProperty } } } => overriddenProperty, _ => null }; for (NamedTypeSymbol currType = containingType.BaseTypeNoUseSiteDiagnostics; (object)currType != null && (object)bestMatch == null && hiddenBuilder == null; currType = currType.BaseTypeNoUseSiteDiagnostics) { bool unused; FindOverriddenOrHiddenMembersInType( member, memberIsFromSomeCompilation, containingType, knownOverriddenMember, currType, out bestMatch, out unused, out hiddenBuilder); } // Based on bestMatch, find other methods that will be overridden, hidden, or runtime overridden // (in bestMatch.ContainingType). FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, bestMatch, out overriddenMembers, ref hiddenBuilder); } public static Symbol FindFirstHiddenMemberIfAny(Symbol member, bool memberIsFromSomeCompilation) { ArrayBuilder<Symbol> hiddenBuilder; FindOverriddenOrHiddenMembers(member, member.ContainingType, memberIsFromSomeCompilation, out hiddenBuilder, overriddenMembers: out _); Symbol result = hiddenBuilder?.FirstOrDefault(); hiddenBuilder?.Free(); return result; } /// <summary> /// Compute a candidate overridden method when a method knows what method it is intended to /// override. This makes a particular difference when covariant returns are used, in which /// case the signature matching rules would not compute the correct overridden method. /// </summary> private static MethodSymbol KnownOverriddenClassMethod(MethodSymbol method) => method switch { PEMethodSymbol m => m.ExplicitlyOverriddenClassMethod, RetargetingMethodSymbol m => m.ExplicitlyOverriddenClassMethod, _ => null }; /// <summary> /// In the CLI, accessors are just regular methods and their overriding/hiding rules are the same as for /// regular methods. In C#, however, accessors are intimately connected with their corresponding properties. /// Rather than walking up the type hierarchy from the containing type of this accessor, looking for members /// with the same name, MakePropertyAccessorOverriddenOrHiddenMembers delegates to the associated property. /// For an accessor to hide a member, the hidden member must be a corresponding accessor on a property hidden /// by the associated property. For an accessor to override a member, the overridden member must be a /// corresponding accessor on a property (directly or indirectly) overridden by the associated property. /// /// Example 1: /// /// public class A { public virtual int P { get; set; } } /// public class B : A { public override int P { get { return 1; } } } //get only /// public class C : B { public override int P { set { } } } // set only /// /// C.P.set overrides A.P.set because C.P.set is the setter of C.P, which overrides B.P, /// which overrides A.P, which has A.P.set as a setter. /// /// Example 2: /// /// public class A { public virtual int P { get; set; } } /// public class B : A { public new virtual int P { get { return 1; } } } //get only /// public class C : B { public override int P { set { } } } // set only /// /// C.P.set does not override any method because C.P overrides B.P, which has no setter /// and does not override a property. /// </summary> /// <param name="accessor">This accessor.</param> /// <param name="associatedProperty">The property associated with this accessor.</param> /// <returns>Members overridden or hidden by this accessor.</returns> /// <remarks> /// This method is intended to return values consistent with the definition of C#, which /// may differ from the actual meaning at runtime. /// /// Note: we don't need a different path for interfaces - Property.OverriddenOrHiddenMembers handles that. /// </remarks> private static OverriddenOrHiddenMembersResult MakePropertyAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, PropertySymbol associatedProperty) { Debug.Assert(accessor.IsAccessor()); Debug.Assert((object)associatedProperty != null); bool accessorIsGetter = accessor.MethodKind == MethodKind.PropertyGet; MethodSymbol overriddenAccessor = null; ArrayBuilder<Symbol> hiddenBuilder = null; OverriddenOrHiddenMembersResult hiddenOrOverriddenByProperty = associatedProperty.OverriddenOrHiddenMembers; foreach (Symbol hiddenByProperty in hiddenOrOverriddenByProperty.HiddenMembers) { if (hiddenByProperty.Kind == SymbolKind.Property) { // If we're looking at the associated property of this method (vs a property // it overrides), then record the corresponding accessor (if any) as hidden. PropertySymbol propertyHiddenByProperty = (PropertySymbol)hiddenByProperty; MethodSymbol correspondingAccessor = accessorIsGetter ? propertyHiddenByProperty.GetMethod : propertyHiddenByProperty.SetMethod; if ((object)correspondingAccessor != null) { AccessOrGetInstance(ref hiddenBuilder).Add(correspondingAccessor); } } } if (hiddenOrOverriddenByProperty.OverriddenMembers.Any()) { // CONSIDER: Do something more sensible if there are multiple overridden members? Already an error case. PropertySymbol propertyOverriddenByProperty = (PropertySymbol)hiddenOrOverriddenByProperty.OverriddenMembers[0]; MethodSymbol correspondingAccessor = accessorIsGetter ? propertyOverriddenByProperty.GetOwnOrInheritedGetMethod() : propertyOverriddenByProperty.GetOwnOrInheritedSetMethod(); if ((object)correspondingAccessor != null) { overriddenAccessor = correspondingAccessor; } } // There's a detailed comment in MakeOverriddenOrHiddenMembersWorker(Symbol) concerning why this predicate is appropriate. bool accessorIsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; ImmutableArray<Symbol> overriddenAccessors = ImmutableArray<Symbol>.Empty; if ((object)overriddenAccessor != null && IsOverriddenSymbolAccessible(overriddenAccessor, accessor.ContainingType) && isAccessorOverride(accessor, overriddenAccessor)) { FindRelatedMembers( accessor.IsOverride, accessorIsFromSomeCompilation, accessor.Kind, overriddenAccessor, out overriddenAccessors, ref hiddenBuilder); } ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenAccessors, hiddenMembers); bool isAccessorOverride(MethodSymbol accessor, MethodSymbol overriddenAccessor) { if (accessorIsFromSomeCompilation) { return MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(accessor, overriddenAccessor); //NB: custom comparer } if (overriddenAccessor.Equals(KnownOverriddenClassMethod(accessor), TypeCompareKind.AllIgnoreOptions)) { return true; } return MemberSignatureComparer.RuntimeSignatureComparer.Equals(accessor, overriddenAccessor); } } /// <summary> /// In the CLI, accessors are just regular methods and their overriding/hiding rules are the same as for /// regular methods. In C#, however, accessors are intimately connected with their corresponding events. /// Rather than walking up the type hierarchy from the containing type of this accessor, looking for members /// with the same name, MakeEventAccessorOverriddenOrHiddenMembers delegates to the associated event. /// For an accessor to hide a member, the hidden member must be a corresponding accessor on a event hidden /// by the associated event. For an accessor to override a member, the overridden member must be a /// corresponding accessor on a event (directly or indirectly) overridden by the associated event. /// </summary> /// <param name="accessor">This accessor.</param> /// <param name="associatedEvent">The event associated with this accessor.</param> /// <returns>Members overridden or hidden by this accessor.</returns> /// <remarks> /// This method is intended to return values consistent with the definition of C#, which /// may differ from the actual meaning at runtime. /// /// Note: we don't need a different path for interfaces - Event.OverriddenOrHiddenMembers handles that. /// /// CONSIDER: It is an error for an event to have only one accessor. Currently, we mimic the behavior for /// properties, for consistency, but an alternative approach would be to say that nothing is overridden. /// /// CONSIDER: is there a way to share code with MakePropertyAccessorOverriddenOrHiddenMembers? /// </remarks> private static OverriddenOrHiddenMembersResult MakeEventAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, EventSymbol associatedEvent) { Debug.Assert(accessor.IsAccessor()); Debug.Assert((object)associatedEvent != null); bool accessorIsAdder = accessor.MethodKind == MethodKind.EventAdd; MethodSymbol overriddenAccessor = null; ArrayBuilder<Symbol> hiddenBuilder = null; OverriddenOrHiddenMembersResult hiddenOrOverriddenByEvent = associatedEvent.OverriddenOrHiddenMembers; foreach (Symbol hiddenByEvent in hiddenOrOverriddenByEvent.HiddenMembers) { if (hiddenByEvent.Kind == SymbolKind.Event) { // If we're looking at the associated event of this method (vs a event // it overrides), then record the corresponding accessor (if any) as hidden. EventSymbol eventHiddenByEvent = (EventSymbol)hiddenByEvent; MethodSymbol correspondingAccessor = accessorIsAdder ? eventHiddenByEvent.AddMethod : eventHiddenByEvent.RemoveMethod; if ((object)correspondingAccessor != null) { AccessOrGetInstance(ref hiddenBuilder).Add(correspondingAccessor); } } } if (hiddenOrOverriddenByEvent.OverriddenMembers.Any()) { // CONSIDER: Do something more sensible if there are multiple overridden members? Already an error case. EventSymbol eventOverriddenByEvent = (EventSymbol)hiddenOrOverriddenByEvent.OverriddenMembers[0]; MethodSymbol correspondingAccessor = eventOverriddenByEvent.GetOwnOrInheritedAccessor(accessorIsAdder); if ((object)correspondingAccessor != null) { overriddenAccessor = correspondingAccessor; } } // There's a detailed comment in MakeOverriddenOrHiddenMembersWorker(Symbol) concerning why this predicate is appropriate. bool accessorIsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; ImmutableArray<Symbol> overriddenAccessors = ImmutableArray<Symbol>.Empty; if ((object)overriddenAccessor != null && IsOverriddenSymbolAccessible(overriddenAccessor, accessor.ContainingType) && (accessorIsFromSomeCompilation ? MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(accessor, overriddenAccessor) //NB: custom comparer : MemberSignatureComparer.RuntimeSignatureComparer.Equals(accessor, overriddenAccessor))) { FindRelatedMembers( accessor.IsOverride, accessorIsFromSomeCompilation, accessor.Kind, overriddenAccessor, out overriddenAccessors, ref hiddenBuilder); } ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenAccessors, hiddenMembers); } /// <summary> /// There are two key reasons why interface overriding/hiding is different from class overriding/hiding: /// 1) interface members never override other members; and /// 2) interfaces can extend multiple interfaces. /// The first difference doesn't require any special handling - as long as the members have IsOverride=false, /// the code for class overriding/hiding does the right thing. /// The second difference is more problematic. For one thing, an interface member can hide a different member in /// each base interface. We only report the first one, but we need to expose all of them in the API. More importantly, /// multiple inheritance raises the possibility of diamond inheritance. Spec section 13.2.5, Interface member access, /// says: "The intuitive rule for hiding in multiple-inheritance interfaces is simply this: If a member is hidden in any /// access path, it is hidden in all access paths." For example, consider the following interfaces: /// /// interface I0 { void M(); } /// interface I1 : I0 { void M(); } /// interface I2 : I0, I1 { void M(); } /// /// I2.M does not hide I0.M, because it is already hidden by I1.M. To make this work, we need to traverse the graph /// of ancestor interfaces in topological order and flag ones later in the enumeration that are hidden along some path. /// </summary> /// <remarks> /// See SymbolPreparer::checkIfaceHiding. /// </remarks> internal static OverriddenOrHiddenMembersResult MakeInterfaceOverriddenOrHiddenMembers(Symbol member, bool memberIsFromSomeCompilation) { Debug.Assert(!member.IsAccessor()); NamedTypeSymbol containingType = member.ContainingType; Debug.Assert(containingType.IsInterfaceType()); PooledHashSet<NamedTypeSymbol> membersOfOtherKindsHidden = PooledHashSet<NamedTypeSymbol>.GetInstance(); PooledHashSet<NamedTypeSymbol> allMembersHidden = PooledHashSet<NamedTypeSymbol>.GetInstance(); // Implies membersOfOtherKindsHidden. ArrayBuilder<Symbol> hiddenBuilder = null; foreach (NamedTypeSymbol currType in containingType.AllInterfacesNoUseSiteDiagnostics) // NB: topologically sorted { if (allMembersHidden.Contains(currType)) { continue; } Symbol currTypeBestMatch; bool currTypeHasSameKindNonMatch; ArrayBuilder<Symbol> currTypeHiddenBuilder; FindOverriddenOrHiddenMembersInType( member, memberIsFromSomeCompilation, containingType, knownOverriddenMember: null, currType, out currTypeBestMatch, out currTypeHasSameKindNonMatch, out currTypeHiddenBuilder); bool haveBestMatch = (object)currTypeBestMatch != null; if (haveBestMatch) { // If our base interface contains a matching member of the same kind, // then we don't need to look any further up this subtree. foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { allMembersHidden.Add(hidden); } AccessOrGetInstance(ref hiddenBuilder).Add(currTypeBestMatch); } if (currTypeHiddenBuilder != null) { // If our base interface contains a matching member of a different kind, then // it will hide all members that aren't of that kind further up the chain. // As a result, nothing of our kind will be visible and we can stop looking. if (!membersOfOtherKindsHidden.Contains(currType)) { if (!haveBestMatch) { foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { allMembersHidden.Add(hidden); } } AccessOrGetInstance(ref hiddenBuilder).AddRange(currTypeHiddenBuilder); } currTypeHiddenBuilder.Free(); } else if (currTypeHasSameKindNonMatch && !haveBestMatch) { // If our base interface contains a (non-matching) member of the same kind, then // it will hide all members that aren't of that kind further up the chain. foreach (var hidden in currType.AllInterfacesNoUseSiteDiagnostics) { membersOfOtherKindsHidden.Add(hidden); } } } membersOfOtherKindsHidden.Free(); allMembersHidden.Free(); // Based on bestMatch, find other methods that will be overridden, hidden, or runtime overridden // (in bestMatch.ContainingType). ImmutableArray<Symbol> overriddenMembers = ImmutableArray<Symbol>.Empty; if (hiddenBuilder != null) { ArrayBuilder<Symbol> hiddenAndRelatedBuilder = null; foreach (Symbol hidden in hiddenBuilder) { FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, hidden, out overriddenMembers, ref hiddenAndRelatedBuilder); Debug.Assert(overriddenMembers.Length == 0); } hiddenBuilder.Free(); hiddenBuilder = hiddenAndRelatedBuilder; } Debug.Assert(overriddenMembers.IsEmpty); ImmutableArray<Symbol> hiddenMembers = hiddenBuilder == null ? ImmutableArray<Symbol>.Empty : hiddenBuilder.ToImmutableAndFree(); return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); } /// <summary> /// Look for overridden or hidden members in a specific type. /// </summary> /// <param name="member">Member that is hiding or overriding.</param> /// <param name="memberIsFromSomeCompilation">True if member is from the current compilation.</param> /// <param name="memberContainingType">The type that contains member (member.ContainingType).</param> /// <param name="knownOverriddenMember">The known overridden member (e.g. in the presence of a metadata methodimpl).</param> /// <param name="currType">The type to search.</param> /// <param name="currTypeBestMatch"> /// A member with the same signature if currTypeHasExactMatch is true, /// a member with (a minimal number of) different custom modifiers if there is one, /// and null otherwise.</param> /// <param name="currTypeHasSameKindNonMatch">True if there's a member with the same name and kind that is not a match.</param> /// <param name="hiddenBuilder">Hidden members (same name, different kind) will be added to this builder.</param> /// <remarks> /// There is some similarity between this member and TypeSymbol.FindPotentialImplicitImplementationMemberDeclaredInType. /// When making changes to this member, think about whether or not they should also be applied in TypeSymbol. /// /// In incorrect or imported code, it is possible that both currTypeBestMatch and hiddenBuilder will be populated. /// </remarks> private static void FindOverriddenOrHiddenMembersInType( Symbol member, bool memberIsFromSomeCompilation, NamedTypeSymbol memberContainingType, Symbol knownOverriddenMember, NamedTypeSymbol currType, out Symbol currTypeBestMatch, out bool currTypeHasSameKindNonMatch, out ArrayBuilder<Symbol> hiddenBuilder) { Debug.Assert(!member.IsAccessor()); currTypeBestMatch = null; currTypeHasSameKindNonMatch = false; hiddenBuilder = null; bool currTypeHasExactMatch = false; int minCustomModifierCount = int.MaxValue; IEqualityComparer<Symbol> exactMatchComparer = memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpCustomModifierOverrideComparer : MemberSignatureComparer.RuntimePlusRefOutSignatureComparer; IEqualityComparer<Symbol> fallbackComparer = memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpOverrideComparer : MemberSignatureComparer.RuntimeSignatureComparer; SymbolKind memberKind = member.Kind; int memberArity = member.GetMemberArity(); foreach (Symbol otherMember in currType.GetMembers(member.Name)) { if (!IsOverriddenSymbolAccessible(otherMember, memberContainingType)) { //do nothing } else if (otherMember.IsAccessor() && !((MethodSymbol)otherMember).IsIndexedPropertyAccessor()) { //Indexed property accessors can be overridden or hidden by non-accessors. //do nothing - no interaction between accessors and non-accessors } else if (otherMember.Kind != memberKind) { // NOTE: generic methods can hide things with arity 0. // From CSemanticChecker::FindSymHiddenByMethPropAgg int otherMemberArity = otherMember.GetMemberArity(); if (otherMemberArity == memberArity || (memberKind == SymbolKind.Method && otherMemberArity == 0)) { AddHiddenMemberIfApplicable(ref hiddenBuilder, memberKind, otherMember); } } else if (!currTypeHasExactMatch) { switch (memberKind) { case SymbolKind.Field: currTypeHasExactMatch = true; currTypeBestMatch = otherMember; break; case SymbolKind.NamedType: if (otherMember.GetMemberArity() == memberArity) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } break; default: if (otherMember.Equals(knownOverriddenMember, TypeCompareKind.AllIgnoreOptions)) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } // We do not perform signature matching in the presence of a methodimpl else if (knownOverriddenMember == null) { if (exactMatchComparer.Equals(member, otherMember)) { currTypeHasExactMatch = true; currTypeBestMatch = otherMember; } else if (fallbackComparer.Equals(member, otherMember)) { // If this method is from source, we'll also consider methods that match // without regard to custom modifiers. If there's more than one, we'll // choose the one with the fewest custom modifiers. int methodCustomModifierCount = CustomModifierCount(otherMember); if (methodCustomModifierCount < minCustomModifierCount) { Debug.Assert(memberIsFromSomeCompilation || minCustomModifierCount == int.MaxValue, "Metadata members require exact custom modifier matches."); minCustomModifierCount = methodCustomModifierCount; currTypeBestMatch = otherMember; } } else { currTypeHasSameKindNonMatch = true; } } break; } } } switch (memberKind) { case SymbolKind.Field: case SymbolKind.NamedType: break; default: // If the member is from metadata, then even a fallback match is an exact match. // We just declined to set the flag at the time in case there was a "better" exact match. // Having said that, there's no reason to update the flag, since no-one will consume it. // if (!memberIsFromSomeCompilation && ((object)currTypeBestMatch != null)) currTypeHasExactMatch = true; // There's a special case where we have to go back and fix up our best match. // If member is from source, then it has no custom modifiers (at least, // until it copies them from the member it overrides, which we're trying to // compute now). Therefore, an exact match will be one that has no custom // modifiers in/on its parameters. The best match may, however, have custom // modifiers in/on its (return) type, since that wasn't considered during the // signature comparison. If that is the case, then we need to make sure that // there isn't another inexact match (i.e. same signature ignoring custom // modifiers) with fewer custom modifiers. // NOTE: If member is constructed, then it has already inherited custom modifiers // from the underlying member and this cleanup is unnecessary. That's why we're // checking member.IsDefinition in addition to memberIsFromSomeCompilation. if (currTypeHasExactMatch && memberIsFromSomeCompilation && member.IsDefinition && TypeOrReturnTypeHasCustomModifiers(currTypeBestMatch)) { #if DEBUG // If there were custom modifiers on the parameters, then the match wouldn't have been // exact and so we would already have applied the custom modifier count as a tie-breaker. foreach (ParameterSymbol param in currTypeBestMatch.GetParameters()) { Debug.Assert(!(param.TypeWithAnnotations.CustomModifiers.Any() || param.RefCustomModifiers.Any())); Debug.Assert(!param.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false)); } #endif Symbol minCustomModifierMatch = currTypeBestMatch; foreach (Symbol otherMember in currType.GetMembers(member.Name)) { if (otherMember.Kind == currTypeBestMatch.Kind && !ReferenceEquals(otherMember, currTypeBestMatch)) { if (MemberSignatureComparer.CSharpOverrideComparer.Equals(otherMember, currTypeBestMatch)) { int customModifierCount = CustomModifierCount(otherMember); if (customModifierCount < minCustomModifierCount) { minCustomModifierCount = customModifierCount; minCustomModifierMatch = otherMember; } } } } currTypeBestMatch = minCustomModifierMatch; } break; } } /// <summary> /// If representative member is non-null and is contained in a constructed type, then find /// other members in the same type with the same signature. If this is an override member, /// add them to the overridden and runtime overridden lists. Otherwise, add them to the /// hidden list. /// </summary> private static void FindRelatedMembers( bool isOverride, bool overridingMemberIsFromSomeCompilation, SymbolKind overridingMemberKind, Symbol representativeMember, out ImmutableArray<Symbol> overriddenMembers, ref ArrayBuilder<Symbol> hiddenBuilder) { overriddenMembers = ImmutableArray<Symbol>.Empty; if ((object)representativeMember != null) { bool needToSearchForRelated = representativeMember.Kind != SymbolKind.Field && representativeMember.Kind != SymbolKind.NamedType && (!representativeMember.ContainingType.IsDefinition || representativeMember.IsIndexer()); if (isOverride) { if (needToSearchForRelated) { ArrayBuilder<Symbol> overriddenBuilder = ArrayBuilder<Symbol>.GetInstance(); overriddenBuilder.Add(representativeMember); FindOtherOverriddenMethodsInContainingType(representativeMember, overridingMemberIsFromSomeCompilation, overriddenBuilder); overriddenMembers = overriddenBuilder.ToImmutableAndFree(); } else { overriddenMembers = ImmutableArray.Create<Symbol>(representativeMember); } } else { AddHiddenMemberIfApplicable(ref hiddenBuilder, overridingMemberKind, representativeMember); if (needToSearchForRelated) { FindOtherHiddenMembersInContainingType(overridingMemberKind, representativeMember, ref hiddenBuilder); } } } } /// <summary> /// Some kinds of methods are not considered to be hideable by certain kinds of members. /// Specifically, methods, properties, and types cannot hide constructors, destructors, /// operators, conversions, or accessors. /// </summary> private static void AddHiddenMemberIfApplicable(ref ArrayBuilder<Symbol> hiddenBuilder, SymbolKind hidingMemberKind, Symbol hiddenMember) { Debug.Assert((object)hiddenMember != null); if (hiddenMember.Kind != SymbolKind.Method || ((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(hidingMemberKind)) { AccessOrGetInstance(ref hiddenBuilder).Add(hiddenMember); } } private static ArrayBuilder<T> AccessOrGetInstance<T>(ref ArrayBuilder<T> builder) { if (builder == null) { builder = ArrayBuilder<T>.GetInstance(); } return builder; } /// <summary> /// Having found the best member to override, we want to find members with the same signature on the /// best member's containing type. /// </summary> /// <param name="representativeMember"> /// The member that we consider to be overridden (may have different custom modifiers from the overriding member). /// Assumed to already be in the overridden and runtime overridden lists. /// </param> /// <param name="overridingMemberIsFromSomeCompilation"> /// If the best match was based on the custom modifier count, rather than the custom modifiers themselves /// (because the overriding member is in the current compilation), then we should use the count when determining /// whether the override is ambiguous. /// </param> /// <param name="overriddenBuilder"> /// If the declaring type is constructed, it's possible that two (or more) members have the same signature /// (including custom modifiers). Return a list of such members so that we can report the ambiguity. /// </param> private static void FindOtherOverriddenMethodsInContainingType(Symbol representativeMember, bool overridingMemberIsFromSomeCompilation, ArrayBuilder<Symbol> overriddenBuilder) { Debug.Assert((object)representativeMember != null); Debug.Assert(representativeMember.Kind == SymbolKind.Property || !representativeMember.ContainingType.IsDefinition); int representativeCustomModifierCount = -1; foreach (Symbol otherMember in representativeMember.ContainingType.GetMembers(representativeMember.Name)) { if (otherMember.Kind == representativeMember.Kind) { if (otherMember != representativeMember) { // NOTE: If the overriding member is from source, then we compared *counts* of custom modifiers, rather // than actually comparing custom modifiers. Hence, we should do the same thing when looking for // ambiguous overrides. if (overridingMemberIsFromSomeCompilation) { if (representativeCustomModifierCount < 0) { representativeCustomModifierCount = representativeMember.CustomModifierCount(); } if (MemberSignatureComparer.CSharpOverrideComparer.Equals(otherMember, representativeMember) && otherMember.CustomModifierCount() == representativeCustomModifierCount) { overriddenBuilder.Add(otherMember); } } else { if (MemberSignatureComparer.CSharpCustomModifierOverrideComparer.Equals(otherMember, representativeMember)) { overriddenBuilder.Add(otherMember); } } } } } } /// <summary> /// Having found that we are hiding a method with exactly the same signature /// (including custom modifiers), we want to find methods with the same signature /// on the declaring type because they will also be hidden. /// (If the declaring type is constructed, it's possible that two or more /// methods have the same signature (including custom modifiers).) /// (If the representative member is an indexer, it's possible that two or more /// properties have the same signature (including custom modifiers, even in a /// non-generic type). /// </summary> /// <param name="hidingMemberKind"> /// This kind of the hiding member. /// </param> /// <param name="representativeMember"> /// The member that we consider to be hidden (must have exactly the same custom modifiers as the hiding member). /// Assumed to already be in hiddenBuilder. /// </param> /// <param name="hiddenBuilder"> /// Will have all other members with the same signature (including custom modifiers) as /// representativeMember added. /// </param> private static void FindOtherHiddenMembersInContainingType(SymbolKind hidingMemberKind, Symbol representativeMember, ref ArrayBuilder<Symbol> hiddenBuilder) { Debug.Assert((object)representativeMember != null); Debug.Assert(representativeMember.Kind != SymbolKind.Field); Debug.Assert(representativeMember.Kind != SymbolKind.NamedType); Debug.Assert(representativeMember.Kind == SymbolKind.Property || !representativeMember.ContainingType.IsDefinition); IEqualityComparer<Symbol> comparer = MemberSignatureComparer.CSharpCustomModifierOverrideComparer; foreach (Symbol otherMember in representativeMember.ContainingType.GetMembers(representativeMember.Name)) { if (otherMember.Kind == representativeMember.Kind) { if (otherMember != representativeMember && comparer.Equals(otherMember, representativeMember)) { AddHiddenMemberIfApplicable(ref hiddenBuilder, hidingMemberKind, otherMember); } } } } private static bool CanOverrideOrHide(Symbol member) { switch (member.Kind) { case SymbolKind.Property: case SymbolKind.Event: // Explicit interface impls don't override or hide. return !member.IsExplicitInterfaceImplementation(); case SymbolKind.Method: MethodSymbol methodSymbol = (MethodSymbol)member; return MethodSymbol.CanOverrideOrHide(methodSymbol.MethodKind) && ReferenceEquals(methodSymbol, methodSymbol.ConstructedFrom); default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static bool TypeOrReturnTypeHasCustomModifiers(Symbol member) { switch (member.Kind) { case SymbolKind.Method: MethodSymbol method = (MethodSymbol)member; var methodReturnType = method.ReturnTypeWithAnnotations; return methodReturnType.CustomModifiers.Any() || method.RefCustomModifiers.Any() || methodReturnType.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); case SymbolKind.Property: PropertySymbol property = (PropertySymbol)member; var propertyType = property.TypeWithAnnotations; return propertyType.CustomModifiers.Any() || property.RefCustomModifiers.Any() || propertyType.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); case SymbolKind.Event: EventSymbol @event = (EventSymbol)member; return @event.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); //can't have custom modifiers on (vs in) type default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static int CustomModifierCount(Symbol member) { switch (member.Kind) { case SymbolKind.Method: MethodSymbol method = (MethodSymbol)member; return method.CustomModifierCount(); case SymbolKind.Property: PropertySymbol property = (PropertySymbol)member; return property.CustomModifierCount(); case SymbolKind.Event: EventSymbol @event = (EventSymbol)member; return @event.Type.CustomModifierCount(); default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } /// <summary> /// Determine if this method requires a methodimpl table entry to inform the runtime of the override relationship. /// </summary> /// <param name="warnAmbiguous">True if we should produce an ambiguity warning per https://github.com/dotnet/roslyn/issues/45453 .</param> internal static bool RequiresExplicitOverride(this MethodSymbol method, out bool warnAmbiguous) { warnAmbiguous = false; if (!method.IsOverride) return false; MethodSymbol csharpOverriddenMethod = method.OverriddenMethod; if (csharpOverriddenMethod is null) return false; MethodSymbol runtimeOverriddenMethod = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out bool wasAmbiguous); if (csharpOverriddenMethod == runtimeOverriddenMethod && !wasAmbiguous) return false; // See https://github.com/dotnet/roslyn/issues/45453. No need to warn when the runtime // supports covariant returns because any methodimpl we produce to identify the specific // overridden method is unambiguously understood by the runtime. if (method.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) return true; // If the method was declared as a covariant return, there will be a compile-time error since the runtime // does not support covariant returns. In this case we do not warn about runtime ambiguity and pretend that // we can use a methodimpl (even though it is of a form not supported by the runtime and would result in a // loader error) so that the symbol APIs produce the most useful result. if (!method.ReturnType.Equals(csharpOverriddenMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) return true; // Due to https://github.com/dotnet/runtime/issues/38119 the methodimpl would // appear to the runtime to be ambiguous in some cases. bool methodimplWouldBeAmbiguous = csharpOverriddenMethod.MethodHasRuntimeCollision(); if (!methodimplWouldBeAmbiguous) return true; Debug.Assert(runtimeOverriddenMethod is { }); // We produce the warning when a methodimpl would be required but would be ambiguous to the runtime. // However, if there was a duplicate definition for the runtime signature of the overridden // method where it was originally declared, that would have been an error. In that case we suppress // the warning as a cascaded diagnostic. bool originalOverriddenMethodWasAmbiguous = csharpOverriddenMethod.IsDefinition || csharpOverriddenMethod.OriginalDefinition.MethodHasRuntimeCollision(); warnAmbiguous = !originalOverriddenMethodWasAmbiguous; bool overriddenMethodContainedInSameTypeAsRuntimeOverriddenMethod = csharpOverriddenMethod.ContainingType.Equals(runtimeOverriddenMethod.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); // If the overridden method is on a different (e.g. base) type compared to the runtime overridden // method, then the runtime overridden method could not possibly resolve correctly to the overridden method. // In this case we might as well produce a methodimpl. At least it has a chance of being correctly resolved // by the runtime, where the runtime resolution without the methodimpl would definitely be wrong. if (!overriddenMethodContainedInSameTypeAsRuntimeOverriddenMethod) return true; // This is the historical test, preserved since the days of the native compiler in case it turns out to affect compatibility. // However, this test cannot be true in a program free of errors. return csharpOverriddenMethod != runtimeOverriddenMethod && method.IsAccessor() != runtimeOverriddenMethod.IsAccessor(); } internal static bool MethodHasRuntimeCollision(this MethodSymbol method) { foreach (Symbol otherMethod in method.ContainingType.GetMembers(method.Name)) { if (otherMethod != method && MemberSignatureComparer.RuntimeSignatureComparer.Equals(otherMethod, method)) { return true; } } return false; } /// <summary> /// Given a method, find the first method that it overrides from the perspective of the CLI. /// Key differences from C#: non-virtual methods are ignored, the RuntimeSignatureComparer /// is used (i.e. consider return types, ignore ref/out distinction). Sets <paramref name="wasAmbiguous"/> /// to true if more than one method is overridden by CLI rules. /// </summary> /// <remarks> /// WARN: Must not check method.MethodKind - PEMethodSymbol.ComputeMethodKind uses this method. /// NOTE: Does not check whether the given method will be marked "newslot" in metadata (as /// "newslot" is used for covariant method overrides). /// </remarks> internal static MethodSymbol GetFirstRuntimeOverriddenMethodIgnoringNewSlot(this MethodSymbol method, out bool wasAmbiguous) { // WARN: If the method may override a source method and declaration diagnostics have yet to // be computed, then it is important for us to pass ignoreInterfaceImplementationChanges: true // (see MethodSymbol.IsMetadataVirtual for details). // Since we are only concerned with overrides (of class methods), interface implementations can be ignored. const bool ignoreInterfaceImplementationChanges = true; wasAmbiguous = false; if (!method.IsMetadataVirtual(ignoreInterfaceImplementationChanges) || method.IsStatic) { return null; } NamedTypeSymbol containingType = method.ContainingType; for (NamedTypeSymbol currType = containingType.BaseTypeNoUseSiteDiagnostics; !ReferenceEquals(currType, null); currType = currType.BaseTypeNoUseSiteDiagnostics) { MethodSymbol candidate = null; foreach (Symbol otherMember in currType.GetMembers(method.Name)) { if (otherMember.Kind == SymbolKind.Method && IsOverriddenSymbolAccessible(otherMember, containingType) && MemberSignatureComparer.RuntimeSignatureComparer.Equals(method, otherMember)) { MethodSymbol overridden = (MethodSymbol)otherMember; // NOTE: The runtime doesn't consider non-virtual methods during override resolution. if (overridden.IsMetadataVirtual(ignoreInterfaceImplementationChanges)) { if (candidate is { }) { // found more than one possible override in this type wasAmbiguous = true; return candidate; } candidate = overridden; } } } if (candidate is { }) { return candidate; } } return null; } /// <remarks> /// Note that the access check is done using the original definitions. This is because we want to avoid /// reductions in accessibility that result from type argument substitution (e.g. if an inaccessible type /// has been passed as a type argument). /// See DevDiv #11967 for an example. /// </remarks> private static bool IsOverriddenSymbolAccessible(Symbol overridden, NamedTypeSymbol overridingContainingType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return AccessCheck.IsSymbolAccessible(overridden.OriginalDefinition, overridingContainingType.OriginalDefinition, ref discardedUseSiteInfo); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/VisualBasicTest/Recommendations/OptionStatements/ExplicitOptionsRecommenderTests.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.OptionStatements Public Class ExplicitOptionsRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionsAfterOptionExplicitTest() VerifyRecommendationsAreExactly(<File>Option Explicit |</File>, "On", "Off") 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.OptionStatements Public Class ExplicitOptionsRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionsAfterOptionExplicitTest() VerifyRecommendationsAreExactly(<File>Option Explicit |</File>, "On", "Off") End Sub End Class End Namespace
-1