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
unknown | date_merged
unknown | 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 | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Test/PdbUtilities/Reader/PdbTestUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
extern alias DSR;
using System;
using System.Collections.Immutable;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using DSR::Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
namespace Roslyn.Test.Utilities
{
public static class PdbTestUtilities
{
public static ISymUnmanagedReader3 CreateSymReader(this CompilationVerifier verifier)
{
var pdbStream = new ImmutableMemoryStream(verifier.EmittedAssemblyPdb);
return SymReaderFactory.CreateReader(pdbStream, metadataReaderOpt: null, metadataMemoryOwnerOpt: null);
}
public static unsafe EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(this ISymUnmanagedReader3 symReader, MethodDefinitionHandle handle)
{
const int S_OK = 0;
if (symReader is ISymUnmanagedReader4 symReader4)
{
int hr = symReader4.GetPortableDebugMetadata(out byte* metadata, out int size);
Marshal.ThrowExceptionForHR(hr);
if (hr == S_OK)
{
var pdbReader = new MetadataReader(metadata, size);
ImmutableArray<byte> GetCdiBytes(Guid kind) =>
TryGetCustomDebugInformation(pdbReader, handle, kind, out var info) ? pdbReader.GetBlobContent(info.Value) : default(ImmutableArray<byte>);
return EditAndContinueMethodDebugInformation.Create(
compressedSlotMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLocalSlotMap),
compressedLambdaMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap));
}
}
var cdi = CustomDebugInfoUtilities.GetCustomDebugInfoBytes(symReader, handle, methodVersion: 1);
if (cdi == null)
{
return EditAndContinueMethodDebugInformation.Create(default(ImmutableArray<byte>), default(ImmutableArray<byte>));
}
return GetEncMethodDebugInfo(cdi);
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
bool foundAny = false;
customDebugInfo = default(CustomDebugInformation);
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
public static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(byte[] customDebugInfoBlob)
{
return EditAndContinueMethodDebugInformation.Create(
CustomDebugInfoUtilities.GetEditAndContinueLocalSlotMapRecord(customDebugInfoBlob),
CustomDebugInfoUtilities.GetEditAndContinueLambdaMapRecord(customDebugInfoBlob));
}
public static string GetTokenToLocationMap(Compilation compilation, bool maskToken = false)
{
using (var exebits = new MemoryStream())
{
using (var pdbbits = new MemoryStream())
{
compilation.Emit(exebits, pdbbits);
return Token2SourceLineExporter.TokenToSourceMap2Xml(pdbbits, maskToken);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
extern alias DSR;
using System;
using System.Collections.Immutable;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using DSR::Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
namespace Roslyn.Test.Utilities
{
public static class PdbTestUtilities
{
public static ISymUnmanagedReader3 CreateSymReader(this CompilationVerifier verifier)
{
var pdbStream = new ImmutableMemoryStream(verifier.EmittedAssemblyPdb);
return SymReaderFactory.CreateReader(pdbStream, metadataReaderOpt: null, metadataMemoryOwnerOpt: null);
}
public static unsafe EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(this ISymUnmanagedReader3 symReader, MethodDefinitionHandle handle)
{
const int S_OK = 0;
if (symReader is ISymUnmanagedReader4 symReader4)
{
int hr = symReader4.GetPortableDebugMetadata(out byte* metadata, out int size);
Marshal.ThrowExceptionForHR(hr);
if (hr == S_OK)
{
var pdbReader = new MetadataReader(metadata, size);
ImmutableArray<byte> GetCdiBytes(Guid kind) =>
TryGetCustomDebugInformation(pdbReader, handle, kind, out var info) ? pdbReader.GetBlobContent(info.Value) : default(ImmutableArray<byte>);
return EditAndContinueMethodDebugInformation.Create(
compressedSlotMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLocalSlotMap),
compressedLambdaMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap));
}
}
var cdi = CustomDebugInfoUtilities.GetCustomDebugInfoBytes(symReader, handle, methodVersion: 1);
if (cdi == null)
{
return EditAndContinueMethodDebugInformation.Create(default(ImmutableArray<byte>), default(ImmutableArray<byte>));
}
return GetEncMethodDebugInfo(cdi);
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
bool foundAny = false;
customDebugInfo = default(CustomDebugInformation);
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
public static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(byte[] customDebugInfoBlob)
{
return EditAndContinueMethodDebugInformation.Create(
CustomDebugInfoUtilities.GetEditAndContinueLocalSlotMapRecord(customDebugInfoBlob),
CustomDebugInfoUtilities.GetEditAndContinueLambdaMapRecord(customDebugInfoBlob));
}
public static string GetTokenToLocationMap(Compilation compilation, bool maskToken = false)
{
using (var exebits = new MemoryStream())
{
using (var pdbbits = new MemoryStream())
{
compilation.Emit(exebits, pdbbits);
return Token2SourceLineExporter.TokenToSourceMap2Xml(pdbbits, maskToken);
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncMethodHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
{|Cursor:[|async|]|} Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
{|Cursor:[|async|]|} Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = [|await|] AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = [|await|] resultTask;
result = [|await|] lambda();
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncMethodHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
{|Cursor:[|async|]|} Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
{|Cursor:[|async|]|} Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = [|await|] AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = [|await|] resultTask;
result = [|await|] lambda();
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Tools/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructure.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure
{
internal sealed class OmniSharpBlockStructure
{
public ImmutableArray<OmniSharpBlockSpan> Spans { get; }
public OmniSharpBlockStructure(ImmutableArray<OmniSharpBlockSpan> spans)
{
Spans = spans;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure
{
internal sealed class OmniSharpBlockStructure
{
public ImmutableArray<OmniSharpBlockSpan> Spans { get; }
public OmniSharpBlockStructure(ImmutableArray<OmniSharpBlockSpan> spans)
{
Spans = spans;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Syntax/Parsing/RefReadonlyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public class RefReadonlyTests : ParsingTests
{
public RefReadonlyTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact]
public void RefReadonlyReturn_CSharp7()
{
var text = @"
unsafe class Program
{
delegate ref readonly int D1();
static ref readonly T M<T>()
{
return ref (new T[1])[0];
}
public virtual ref readonly int* P1 => throw null;
public ref readonly int[][] this[int i] => throw null;
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (4,18): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// delegate ref readonly int D1();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(4, 18),
// (6,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// static ref readonly T M<T>()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(6, 16),
// (11,24): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// public virtual ref readonly int* P1 => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(11, 24),
// (13,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// public ref readonly int[][] this[int i] => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(13, 16)
);
}
[Fact]
public void InArgs_CSharp7()
{
var text = @"
class Program
{
static void M(in int x)
{
}
int this[in int x]
{
get
{
return 1;
}
}
static void Test1()
{
int x = 1;
M(in x);
_ = (new Program())[in x];
}
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (4,19): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// static void M(in int x)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(4, 19),
// (8,14): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// int this[in int x]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(8, 14),
// (19,11): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// M(in x);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(19, 11),
// (21,29): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// _ = (new Program())[in x];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(21, 29)
);
}
[Fact]
public void RefReadonlyReturn_Unexpected()
{
var text = @"
class Program
{
static void Main()
{
}
ref readonly int Field;
public static ref readonly Program operator +(Program x, Program y)
{
throw null;
}
// this parses fine
static async ref readonly Task M<T>()
{
throw null;
}
public ref readonly virtual int* P1 => throw null;
}
";
ParseAndValidate(text, TestOptions.Regular9,
// (9,27): error CS1003: Syntax error, '(' expected
// ref readonly int Field;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(9, 27),
// (9,27): error CS1026: ) expected
// ref readonly int Field;
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(9, 27),
// (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly Program operator +(Program x, Program y)
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41),
// (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly Program operator +(Program x, Program y)
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41),
// (12,5): error CS1519: Invalid token '{' ref readonly class, struct, or interface member declaration
// {
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5),
// (12,5): error CS1519: Invalid token '{' in class, record, struct, or interface member declaration
// {
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5),
// (17,5): error CS8803: Top-level statements must precede namespace and type declarations.
// static async ref readonly Task M<T>()
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"static async ref readonly Task M<T>()
{
throw null;
}").WithLocation(17, 5),
// (22,25): error CS1031: Type expected
// public ref readonly virtual int* P1 => throw null;
Diagnostic(ErrorCode.ERR_TypeExpected, "virtual").WithLocation(22, 25),
// (24,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(24, 1));
}
[Fact]
public void RefReadonlyReturn_UnexpectedBindTime()
{
var text = @"
class Program
{
static void Main()
{
ref readonly int local = ref (new int[1])[0];
(ref readonly int, ref readonly int Alice)? t = null;
System.Collections.Generic.List<ref readonly int> x = null;
Use(local);
Use(t);
Use(x);
}
static void Use<T>(T dummy)
{
}
}
";
var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef });
comp.VerifyDiagnostics(
// (9,10): error CS1073: Unexpected token 'ref'
// (ref readonly int, ref readonly int Alice)? t = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 10),
// (9,28): error CS1073: Unexpected token 'ref'
// (ref readonly int, ref readonly int Alice)? t = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 28),
// (11,41): error CS1073: Unexpected token 'ref'
// System.Collections.Generic.List<ref readonly int> x = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(11, 41));
}
[Fact]
public void RefReadOnlyLocalsAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
int value = 0;
ref int valid = ref value;
ref readonly int invalid = ref readonly value;
}
}").GetParseDiagnostics().Verify(
// (8,40): error CS1525: Invalid expression term 'readonly'
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 40),
// (8,40): error CS1002: ; expected
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 40),
// (8,40): error CS0106: The modifier 'readonly' is not valid for this item
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 40),
// (8,54): error CS1001: Identifier expected
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 54));
}
[Fact]
public void LocalsWithRefReadOnlyExpressionsAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
int value = 0;
ref int valid = ref value;
ref int invalid = ref readonly value;
}
}").GetParseDiagnostics().Verify(
// (8,31): error CS1525: Invalid expression term 'readonly'
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 31),
// (8,31): error CS1002: ; expected
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 31),
// (8,31): error CS0106: The modifier 'readonly' is not valid for this item
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 31),
// (8,45): error CS1001: Identifier expected
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 45));
}
[Fact]
public void ReturnRefReadOnlyAreDisallowed()
{
CreateCompilation(@"
class Test
{
int value = 0;
ref readonly int Valid() => ref value;
ref readonly int Invalid() => ref readonly value;
}").GetParseDiagnostics().Verify(
// (7,39): error CS1525: Invalid expression term 'readonly'
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(7, 39),
// (7,39): error CS1002: ; expected
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(7, 39),
// (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53),
// (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53));
}
[Fact]
public void RefReadOnlyForEachAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
var ar = new int[] { 1, 2, 3 };
foreach(ref readonly v in ar)
{
}
}
}").GetParseDiagnostics().Verify(
// (8,17): error CS1525: Invalid expression term 'ref'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(8, 17),
// (8,21): error CS1525: Invalid expression term 'readonly'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,21): error CS1515: 'in' expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InExpected, "readonly").WithLocation(8, 21),
// (8,21): error CS0230: Type and identifier are both required in a foreach statement
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_BadForeachDecl, "readonly").WithLocation(8, 21),
// (8,21): error CS1525: Invalid expression term 'readonly'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,21): error CS1026: ) expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(8, 21),
// (8,21): error CS0106: The modifier 'readonly' is not valid for this item
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,32): error CS1001: Identifier expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_IdentifierExpected, "in").WithLocation(8, 32),
// (8,32): error CS1003: Syntax error, ',' expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SyntaxError, "in").WithArguments(",", "in").WithLocation(8, 32),
// (8,35): error CS1002: ; expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "ar").WithLocation(8, 35),
// (8,37): error CS1002: ; expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 37),
// (8,37): error CS1513: } expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 37));
}
[Fact]
public void RefReadOnlyAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(ref readonly x);
}
}").GetParseDiagnostics().Verify(
// (10,15): error CS1525: Invalid expression term 'readonly'
// M(in x);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(10, 15),
// (10,15): error CS1026: ) expected
// M(in x);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(10, 15),
// (10,15): error CS1002: ; expected
// M(in x);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(10, 15),
// (10,15): error CS0106: The modifier 'readonly' is not valid for this item
// M(in x);
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(10, 15),
// (10,25): error CS1001: Identifier expected
// M(in x);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 25),
// (10,25): error CS1002: ; expected
// M(in x);
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(10, 25),
// (10,25): error CS1513: } expected
// M(in x);
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(10, 25));
}
[Fact]
public void InAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(in x);
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void NothingAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(x);
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void InverseReadOnlyRefShouldBeIllegal()
{
CreateCompilation(@"
class Test
{
void M(readonly ref int p)
{
}
}").GetParseDiagnostics().Verify(
// (4,12): error CS1026: ) expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 12),
// (4,12): error CS1002: ; expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 12),
// (4,30): error CS1003: Syntax error, '(' expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("(", ")").WithLocation(4, 30));
}
[Fact]
public void RefReadOnlyReturnIllegalInOperators()
{
CreateCompilation(@"
public class Test
{
public static ref readonly bool operator!(Test obj) => throw null;
}").GetParseDiagnostics().Verify(
// (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37),
// (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37),
// (4,55): error CS8124: Tuple must contain at least two elements.
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 55),
// (4,57): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 57));
}
[Fact]
public void InNotAllowedInReturnType()
{
CreateCompilation(@"
class Test
{
in int M() => throw null;
}").VerifyDiagnostics(
// (4,5): error CS1519: Invalid token 'in' in class, record, struct, or interface member declaration
// in int M() => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "in").WithArguments("in").WithLocation(4, 5));
}
[Fact]
public void RefReadOnlyNotAllowedInParameters()
{
CreateCompilation(@"
class Test
{
void M(ref readonly int p) => throw null;
}").VerifyDiagnostics(
// (4,16): error CS1031: Type expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_TypeExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1001: Identifier expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1026: ) expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1002: ; expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 16),
// (4,30): error CS1003: Syntax error, ',' expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(4, 30),
// (4,10): error CS0501: 'Test.M(ref ?)' must declare a body because it is not marked abstract, extern, or partial
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("Test.M(ref ?)").WithLocation(4, 10),
// (4,29): warning CS0169: The field 'Test.p' is never used
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("Test.p").WithLocation(4, 29));
}
[Fact, WorkItem(25264, "https://github.com/dotnet/roslyn/issues/25264")]
public void TestNewRefArray()
{
UsingStatement("new ref[];",
// (1,8): error CS1031: Type expected
// new ref[];
Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(1, 8));
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.ArrayType);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
}
M(SyntaxKind.ArgumentList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public class RefReadonlyTests : ParsingTests
{
public RefReadonlyTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact]
public void RefReadonlyReturn_CSharp7()
{
var text = @"
unsafe class Program
{
delegate ref readonly int D1();
static ref readonly T M<T>()
{
return ref (new T[1])[0];
}
public virtual ref readonly int* P1 => throw null;
public ref readonly int[][] this[int i] => throw null;
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (4,18): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// delegate ref readonly int D1();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(4, 18),
// (6,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// static ref readonly T M<T>()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(6, 16),
// (11,24): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// public virtual ref readonly int* P1 => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(11, 24),
// (13,16): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// public ref readonly int[][] this[int i] => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "readonly").WithArguments("readonly references", "7.2").WithLocation(13, 16)
);
}
[Fact]
public void InArgs_CSharp7()
{
var text = @"
class Program
{
static void M(in int x)
{
}
int this[in int x]
{
get
{
return 1;
}
}
static void Test1()
{
int x = 1;
M(in x);
_ = (new Program())[in x];
}
}
";
var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (4,19): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// static void M(in int x)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(4, 19),
// (8,14): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// int this[in int x]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(8, 14),
// (19,11): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// M(in x);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(19, 11),
// (21,29): error CS8302: Feature 'readonly references' is not available in C# 7.1. Please use language version 7.2 or greater.
// _ = (new Program())[in x];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "in").WithArguments("readonly references", "7.2").WithLocation(21, 29)
);
}
[Fact]
public void RefReadonlyReturn_Unexpected()
{
var text = @"
class Program
{
static void Main()
{
}
ref readonly int Field;
public static ref readonly Program operator +(Program x, Program y)
{
throw null;
}
// this parses fine
static async ref readonly Task M<T>()
{
throw null;
}
public ref readonly virtual int* P1 => throw null;
}
";
ParseAndValidate(text, TestOptions.Regular9,
// (9,27): error CS1003: Syntax error, '(' expected
// ref readonly int Field;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(9, 27),
// (9,27): error CS1026: ) expected
// ref readonly int Field;
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(9, 27),
// (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly Program operator +(Program x, Program y)
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41),
// (11,41): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly Program operator +(Program x, Program y)
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(11, 41),
// (12,5): error CS1519: Invalid token '{' ref readonly class, struct, or interface member declaration
// {
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5),
// (12,5): error CS1519: Invalid token '{' in class, record, struct, or interface member declaration
// {
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "{").WithArguments("{").WithLocation(12, 5),
// (17,5): error CS8803: Top-level statements must precede namespace and type declarations.
// static async ref readonly Task M<T>()
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"static async ref readonly Task M<T>()
{
throw null;
}").WithLocation(17, 5),
// (22,25): error CS1031: Type expected
// public ref readonly virtual int* P1 => throw null;
Diagnostic(ErrorCode.ERR_TypeExpected, "virtual").WithLocation(22, 25),
// (24,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(24, 1));
}
[Fact]
public void RefReadonlyReturn_UnexpectedBindTime()
{
var text = @"
class Program
{
static void Main()
{
ref readonly int local = ref (new int[1])[0];
(ref readonly int, ref readonly int Alice)? t = null;
System.Collections.Generic.List<ref readonly int> x = null;
Use(local);
Use(t);
Use(x);
}
static void Use<T>(T dummy)
{
}
}
";
var comp = CreateCompilationWithMscorlib45(text, new[] { ValueTupleRef, SystemRuntimeFacadeRef });
comp.VerifyDiagnostics(
// (9,10): error CS1073: Unexpected token 'ref'
// (ref readonly int, ref readonly int Alice)? t = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 10),
// (9,28): error CS1073: Unexpected token 'ref'
// (ref readonly int, ref readonly int Alice)? t = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 28),
// (11,41): error CS1073: Unexpected token 'ref'
// System.Collections.Generic.List<ref readonly int> x = null;
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(11, 41));
}
[Fact]
public void RefReadOnlyLocalsAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
int value = 0;
ref int valid = ref value;
ref readonly int invalid = ref readonly value;
}
}").GetParseDiagnostics().Verify(
// (8,40): error CS1525: Invalid expression term 'readonly'
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 40),
// (8,40): error CS1002: ; expected
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 40),
// (8,40): error CS0106: The modifier 'readonly' is not valid for this item
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 40),
// (8,54): error CS1001: Identifier expected
// ref readonly int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 54));
}
[Fact]
public void LocalsWithRefReadOnlyExpressionsAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
int value = 0;
ref int valid = ref value;
ref int invalid = ref readonly value;
}
}").GetParseDiagnostics().Verify(
// (8,31): error CS1525: Invalid expression term 'readonly'
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 31),
// (8,31): error CS1002: ; expected
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(8, 31),
// (8,31): error CS0106: The modifier 'readonly' is not valid for this item
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 31),
// (8,45): error CS1001: Identifier expected
// ref int invalid = ref readonly value;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(8, 45));
}
[Fact]
public void ReturnRefReadOnlyAreDisallowed()
{
CreateCompilation(@"
class Test
{
int value = 0;
ref readonly int Valid() => ref value;
ref readonly int Invalid() => ref readonly value;
}").GetParseDiagnostics().Verify(
// (7,39): error CS1525: Invalid expression term 'readonly'
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(7, 39),
// (7,39): error CS1002: ; expected
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(7, 39),
// (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53),
// (7,53): error CS1519: Invalid token ';' ref readonly class, struct, or interface member declaration
// ref readonly int Invalid() => ref readonly value;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(7, 53));
}
[Fact]
public void RefReadOnlyForEachAreDisallowed()
{
CreateCompilation(@"
class Test
{
void M()
{
var ar = new int[] { 1, 2, 3 };
foreach(ref readonly v in ar)
{
}
}
}").GetParseDiagnostics().Verify(
// (8,17): error CS1525: Invalid expression term 'ref'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(8, 17),
// (8,21): error CS1525: Invalid expression term 'readonly'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,21): error CS1515: 'in' expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InExpected, "readonly").WithLocation(8, 21),
// (8,21): error CS0230: Type and identifier are both required in a foreach statement
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_BadForeachDecl, "readonly").WithLocation(8, 21),
// (8,21): error CS1525: Invalid expression term 'readonly'
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,21): error CS1026: ) expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(8, 21),
// (8,21): error CS0106: The modifier 'readonly' is not valid for this item
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 21),
// (8,32): error CS1001: Identifier expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_IdentifierExpected, "in").WithLocation(8, 32),
// (8,32): error CS1003: Syntax error, ',' expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SyntaxError, "in").WithArguments(",", "in").WithLocation(8, 32),
// (8,35): error CS1002: ; expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "ar").WithLocation(8, 35),
// (8,37): error CS1002: ; expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 37),
// (8,37): error CS1513: } expected
// foreach(ref readonly v in ar)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 37));
}
[Fact]
public void RefReadOnlyAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(ref readonly x);
}
}").GetParseDiagnostics().Verify(
// (10,15): error CS1525: Invalid expression term 'readonly'
// M(in x);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "readonly").WithArguments("readonly").WithLocation(10, 15),
// (10,15): error CS1026: ) expected
// M(in x);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(10, 15),
// (10,15): error CS1002: ; expected
// M(in x);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(10, 15),
// (10,15): error CS0106: The modifier 'readonly' is not valid for this item
// M(in x);
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(10, 15),
// (10,25): error CS1001: Identifier expected
// M(in x);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 25),
// (10,25): error CS1002: ; expected
// M(in x);
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(10, 25),
// (10,25): error CS1513: } expected
// M(in x);
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(10, 25));
}
[Fact]
public void InAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(in x);
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void NothingAtCallSite()
{
CreateCompilation(@"
class Test
{
void M(in int p)
{
}
void N()
{
int x = 0;
M(x);
}
}").GetParseDiagnostics().Verify();
}
[Fact]
public void InverseReadOnlyRefShouldBeIllegal()
{
CreateCompilation(@"
class Test
{
void M(readonly ref int p)
{
}
}").GetParseDiagnostics().Verify(
// (4,12): error CS1026: ) expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 12),
// (4,12): error CS1002: ; expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 12),
// (4,30): error CS1003: Syntax error, '(' expected
// void M(readonly ref int p)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("(", ")").WithLocation(4, 30));
}
[Fact]
public void RefReadOnlyReturnIllegalInOperators()
{
CreateCompilation(@"
public class Test
{
public static ref readonly bool operator!(Test obj) => throw null;
}").GetParseDiagnostics().Verify(
// (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37),
// (4,37): error CS1519: Invalid token 'operator' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "operator").WithArguments("operator").WithLocation(4, 37),
// (4,55): error CS8124: Tuple must contain at least two elements.
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 55),
// (4,57): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration
// public static ref readonly bool operator!(Test obj) => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 57));
}
[Fact]
public void InNotAllowedInReturnType()
{
CreateCompilation(@"
class Test
{
in int M() => throw null;
}").VerifyDiagnostics(
// (4,5): error CS1519: Invalid token 'in' in class, record, struct, or interface member declaration
// in int M() => throw null;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "in").WithArguments("in").WithLocation(4, 5));
}
[Fact]
public void RefReadOnlyNotAllowedInParameters()
{
CreateCompilation(@"
class Test
{
void M(ref readonly int p) => throw null;
}").VerifyDiagnostics(
// (4,16): error CS1031: Type expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_TypeExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1001: Identifier expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1026: ) expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_CloseParenExpected, "readonly").WithLocation(4, 16),
// (4,16): error CS1002: ; expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "readonly").WithLocation(4, 16),
// (4,30): error CS1003: Syntax error, ',' expected
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(4, 30),
// (4,10): error CS0501: 'Test.M(ref ?)' must declare a body because it is not marked abstract, extern, or partial
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("Test.M(ref ?)").WithLocation(4, 10),
// (4,29): warning CS0169: The field 'Test.p' is never used
// void M(ref readonly int p) => throw null;
Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("Test.p").WithLocation(4, 29));
}
[Fact, WorkItem(25264, "https://github.com/dotnet/roslyn/issues/25264")]
public void TestNewRefArray()
{
UsingStatement("new ref[];",
// (1,8): error CS1031: Type expected
// new ref[];
Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(1, 8));
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.ArrayType);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
}
M(SyntaxKind.ArgumentList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/CSharp/Test/CallHierarchy/CSharpCallHierarchyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy
{
[UseExportProvider]
public class CSharpCallHierarchyTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnMethod()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnProperty()
{
var text = @"
namespace N
{
class C
{
public int G$$oo { get; set;}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnEvent()
{
var text = @"
using System;
namespace N
{
class C
{
public event EventHandler Go$$o;
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_FindCalls()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
class G
{
void Main()
{
var c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_InterfaceImplementation()
{
var text = @"
namespace N
{
interface I
{
void Goo();
}
class C : I
{
public void G$$oo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToOverride()
{
var text = @"
namespace N
{
class C
{
protected virtual void G$$oo() { }
}
class D : C
{
protected override void Goo() { }
void Bar()
{
C c;
c.Goo()
}
void Baz()
{
D d;
d.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" });
testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" });
}
[WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToBase()
{
var text = @"
namespace N
{
class C
{
protected virtual void Goo() { }
}
class D : C
{
protected override void Goo() { }
void Bar()
{
C c;
c.Goo()
}
void Baz()
{
D d;
d.Go$$o();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldInitializers()
{
var text = @"
namespace N
{
class C
{
public int goo = Goo();
protected int Goo$$() { return 0; }
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") });
testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldReferences()
{
var text = @"
namespace N
{
class C
{
public int g$$oo = Goo();
protected int Goo() { goo = 3; }
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void PropertyGet()
{
var text = @"
namespace N
{
class C
{
public int val
{
g$$et
{
return 0;
}
}
public int goo()
{
var x = this.val;
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Generic()
{
var text = @"
namespace N
{
class C
{
public int gen$$eric<T>(this string generic, ref T stuff)
{
return 0;
}
public int goo()
{
int i;
generic("", ref i);
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void ExtensionMethods()
{
var text = @"
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var x = ""string"";
x.BarStr$$ing();
}
}
public static class Extensions
{
public static string BarString(this string s)
{
return s;
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void GenericExtensionMethods()
{
var text = @"
using System.Collections.Generic;
using System.Linq;
namespace N
{
class Program
{
static void Main(string[] args)
{
List<int> x = new List<int>();
var z = x.Si$$ngle();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InterfaceImplementors()
{
var text = @"
namespace N
{
interface I
{
void Go$$o();
}
class C : I
{
public async Task Goo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void NoFindOverridesOnSealedMethod()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FindOverrides()
{
var text = @"
namespace N
{
class C
{
public virtual void G$$oo()
{
}
}
class G : C
{
public override void Goo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" });
}
[WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void AbstractMethodInclusionToOverrides()
{
var text = @"
using System;
abstract class Base
{
public abstract void $$M();
}
class Derived : Base
{
public override void M()
{
throw new NotImplementedException();
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void SearchAfterEditWorks()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */");
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" });
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy
{
[UseExportProvider]
public class CSharpCallHierarchyTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnMethod()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnProperty()
{
var text = @"
namespace N
{
class C
{
public int G$$oo { get; set;}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnEvent()
{
var text = @"
using System;
namespace N
{
class C
{
public event EventHandler Go$$o;
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_FindCalls()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
class G
{
void Main()
{
var c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_InterfaceImplementation()
{
var text = @"
namespace N
{
interface I
{
void Goo();
}
class C : I
{
public void G$$oo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToOverride()
{
var text = @"
namespace N
{
class C
{
protected virtual void G$$oo() { }
}
class D : C
{
protected override void Goo() { }
void Bar()
{
C c;
c.Goo()
}
void Baz()
{
D d;
d.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" });
testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" });
}
[WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToBase()
{
var text = @"
namespace N
{
class C
{
protected virtual void Goo() { }
}
class D : C
{
protected override void Goo() { }
void Bar()
{
C c;
c.Goo()
}
void Baz()
{
D d;
d.Go$$o();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldInitializers()
{
var text = @"
namespace N
{
class C
{
public int goo = Goo();
protected int Goo$$() { return 0; }
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") });
testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldReferences()
{
var text = @"
namespace N
{
class C
{
public int g$$oo = Goo();
protected int Goo() { goo = 3; }
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void PropertyGet()
{
var text = @"
namespace N
{
class C
{
public int val
{
g$$et
{
return 0;
}
}
public int goo()
{
var x = this.val;
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Generic()
{
var text = @"
namespace N
{
class C
{
public int gen$$eric<T>(this string generic, ref T stuff)
{
return 0;
}
public int goo()
{
int i;
generic("", ref i);
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void ExtensionMethods()
{
var text = @"
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var x = ""string"";
x.BarStr$$ing();
}
}
public static class Extensions
{
public static string BarString(this string s)
{
return s;
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void GenericExtensionMethods()
{
var text = @"
using System.Collections.Generic;
using System.Linq;
namespace N
{
class Program
{
static void Main(string[] args)
{
List<int> x = new List<int>();
var z = x.Si$$ngle();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InterfaceImplementors()
{
var text = @"
namespace N
{
interface I
{
void Go$$o();
}
class C : I
{
public async Task Goo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Goo();
}
void Main2()
{
var c = new C();
c.Goo();
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void NoFindOverridesOnSealedMethod()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FindOverrides()
{
var text = @"
namespace N
{
class C
{
public virtual void G$$oo()
{
}
}
class G : C
{
public override void Goo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" });
}
[WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void AbstractMethodInclusionToOverrides()
{
var text = @"
using System;
abstract class Base
{
public abstract void $$M();
}
class Derived : Base
{
public override void M()
{
throw new NotImplementedException();
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void SearchAfterEditWorks()
{
var text = @"
namespace N
{
class C
{
void G$$oo()
{
}
}
}";
using var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */");
testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" });
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.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.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement
<Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)>
Public NotInheritable Class IntroduceUsingStatementTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider
End Function
<Theory>
<InlineData("D[||]im name = disposable")>
<InlineData("Dim[||] name = disposable")>
<InlineData("Dim [||]name = disposable")>
<InlineData("Dim na[||]me = disposable")>
<InlineData("Dim name[||] = disposable")>
<InlineData("Dim name [||]= disposable")>
<InlineData("Dim name =[||] disposable")>
<InlineData("Dim name = [||]disposable")>
<InlineData("[|Dim name = disposable|]")>
<InlineData("Dim name = disposable[||]")>
<InlineData("Dim name = disposable[||]")>
Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForVerticalSelection() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable) [| " & "
Dim name = disposable |]
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
[||]Dim name = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
[||] Dim name = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name = disposable[||]
Dim ignore = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
Dim ignore = disposable
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name = disposable [||]
Dim ignore = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
Dim ignore = disposable
End Sub
End Class")
End Function
<Theory>
<InlineData("Dim name = d[||]isposable")>
<InlineData("Dim name = disposabl[||]e")>
<InlineData("Dim name=[|disposable|]")>
Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name As System.IDisposable =[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Using [||]name = disposable
End Using
End Sub
End Class")
End Function
<Theory>
<InlineData("[||]Dim x = disposable, y = disposable")>
<InlineData("Dim [||]x = disposable, y = disposable")>
<InlineData("Dim x = disposable, [||]y = disposable")>
<InlineData("Dim x = disposable, y = disposable[||]")>
Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable)
Sub M(disposable As T)
Dim x = disposable[||]
End Sub
End Class", "Class C(Of T As System.IDisposable)
Sub M(disposable As T)
Using x = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task
Await TestMissingAsync("Class C(Of T)
Sub M(disposable as T)
Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
' Comment
Dim x = disposable[||]
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
' Comment
Using x = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||] ' Comment
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable ' Comment
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||]
' Comment
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable
End Using
' Comment
End Sub
End Class")
End Function
<Fact>
Public Async Function ValidPreprocessorStaysValid() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
#If True Then
Dim x = disposable[||]
#End If
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
#If True Then
Using x = disposable
End Using
#End If
End Sub
End Class")
End Function
<Fact>
Public Async Function InvalidPreprocessorStaysInvalid() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
#If True Then
Dim x = disposable[||]
#End If
Dim discard = x
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
#If True Then
Using x = disposable
#End If
Dim discard = x
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function StatementsAreSurroundedByMinimalScope() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
M(null)
Dim x = disposable[||]
M(null)
M(x)
M(null)
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
M(null)
Using x = disposable
M(null)
M(x)
End Using
M(null)
End Sub
End Class")
End Function
<Fact>
Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||]
' A
M(x) ' B
' C
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable
' A
M(x) ' B
End Using
' C
End Sub
End Class")
End Function
<Fact>
Public Async Function WorksInSelectCases() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Select Case disposable
Case Else
Dim x = disposable[||]
M(x)
End Select
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Select Case disposable
Case Else
Using x = disposable
M(x)
End Using
End Select
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
If disposable IsNot Nothing Then Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
If disposable IsNot Nothing Then Else Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
New Action(Function() Dim x = disposable[||])
End Sub
End Class")
End Function
<Fact>
<WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")>
Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Imports System.IO
Class C
Sub M()
Dim reader = New MemoryStream()[||]
Dim buffer = reader.GetBuffer()
buffer.Clone()
Dim a = 1
End Sub
End Class",
"Imports System.IO
Class C
Sub M()
Using reader = New MemoryStream()
Dim buffer = reader.GetBuffer()
buffer.Clone()
End Using
Dim a = 1
End Sub
End Class")
End Function
<Fact>
<WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")>
Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Imports System.IO
Class C
Sub M()
Dim reader = New MemoryStream()[||]
Dim buffer = reader.GetBuffer()
Dim a As Integer = buffer(0), b As Integer = a
Dim c = b
Dim d = 1
End Sub
End Class",
"Imports System.IO
Class C
Sub M()
Using reader = New MemoryStream()
Dim buffer = reader.GetBuffer()
Dim a As Integer = buffer(0), b As Integer = a
Dim c = b
End Using
Dim d = 1
End Sub
End Class")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement
<Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)>
Public NotInheritable Class IntroduceUsingStatementTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider
End Function
<Theory>
<InlineData("D[||]im name = disposable")>
<InlineData("Dim[||] name = disposable")>
<InlineData("Dim [||]name = disposable")>
<InlineData("Dim na[||]me = disposable")>
<InlineData("Dim name[||] = disposable")>
<InlineData("Dim name [||]= disposable")>
<InlineData("Dim name =[||] disposable")>
<InlineData("Dim name = [||]disposable")>
<InlineData("[|Dim name = disposable|]")>
<InlineData("Dim name = disposable[||]")>
<InlineData("Dim name = disposable[||]")>
Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForVerticalSelection() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable) [| " & "
Dim name = disposable |]
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
[||]Dim name = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
[||] Dim name = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Dim ignore = disposable
Using name = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name = disposable[||]
Dim ignore = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
Dim ignore = disposable
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name = disposable [||]
Dim ignore = disposable
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using name = disposable
End Using
Dim ignore = disposable
End Sub
End Class")
End Function
<Theory>
<InlineData("Dim name = d[||]isposable")>
<InlineData("Dim name = disposabl[||]e")>
<InlineData("Dim name=[|disposable|]")>
Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim name As System.IDisposable =[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Using [||]name = disposable
End Using
End Sub
End Class")
End Function
<Theory>
<InlineData("[||]Dim x = disposable, y = disposable")>
<InlineData("Dim [||]x = disposable, y = disposable")>
<InlineData("Dim x = disposable, [||]y = disposable")>
<InlineData("Dim x = disposable, y = disposable[||]")>
Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
" & declaration & "
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable)
Sub M(disposable As T)
Dim x = disposable[||]
End Sub
End Class", "Class C(Of T As System.IDisposable)
Sub M(disposable As T)
Using x = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task
Await TestMissingAsync("Class C(Of T)
Sub M(disposable as T)
Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
' Comment
Dim x = disposable[||]
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
' Comment
Using x = disposable
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||] ' Comment
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable ' Comment
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||]
' Comment
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable
End Using
' Comment
End Sub
End Class")
End Function
<Fact>
Public Async Function ValidPreprocessorStaysValid() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
#If True Then
Dim x = disposable[||]
#End If
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
#If True Then
Using x = disposable
End Using
#End If
End Sub
End Class")
End Function
<Fact>
Public Async Function InvalidPreprocessorStaysInvalid() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
#If True Then
Dim x = disposable[||]
#End If
Dim discard = x
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
#If True Then
Using x = disposable
#End If
Dim discard = x
End Using
End Sub
End Class")
End Function
<Fact>
Public Async Function StatementsAreSurroundedByMinimalScope() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
M(null)
Dim x = disposable[||]
M(null)
M(x)
M(null)
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
M(null)
Using x = disposable
M(null)
M(x)
End Using
M(null)
End Sub
End Class")
End Function
<Fact>
Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Dim x = disposable[||]
' A
M(x) ' B
' C
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Using x = disposable
' A
M(x) ' B
End Using
' C
End Sub
End Class")
End Function
<Fact>
Public Async Function WorksInSelectCases() As Task
Await TestInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
Select Case disposable
Case Else
Dim x = disposable[||]
M(x)
End Select
End Sub
End Class", "Class C
Sub M(disposable As System.IDisposable)
Select Case disposable
Case Else
Using x = disposable
M(x)
End Using
End Select
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
If disposable IsNot Nothing Then Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
If disposable IsNot Nothing Then Else Dim x = disposable[||]
End Sub
End Class")
End Function
<Fact>
Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(disposable As System.IDisposable)
New Action(Function() Dim x = disposable[||])
End Sub
End Class")
End Function
<Fact>
<WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")>
Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Imports System.IO
Class C
Sub M()
Dim reader = New MemoryStream()[||]
Dim buffer = reader.GetBuffer()
buffer.Clone()
Dim a = 1
End Sub
End Class",
"Imports System.IO
Class C
Sub M()
Using reader = New MemoryStream()
Dim buffer = reader.GetBuffer()
buffer.Clone()
End Using
Dim a = 1
End Sub
End Class")
End Function
<Fact>
<WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")>
Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Imports System.IO
Class C
Sub M()
Dim reader = New MemoryStream()[||]
Dim buffer = reader.GetBuffer()
Dim a As Integer = buffer(0), b As Integer = a
Dim c = b
Dim d = 1
End Sub
End Class",
"Imports System.IO
Class C
Sub M()
Using reader = New MemoryStream()
Dim buffer = reader.GetBuffer()
Dim a As Integer = buffer(0), b As Integer = a
Dim c = b
End Using
Dim d = 1
End Sub
End Class")
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.it.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../CSharpCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../CSharpCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/InternalUtilities/IsExternalInit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Copied from:
// https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Copied from:
// https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/DeclarationContext.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend MustInherit Class DeclarationContext
Inherits BlockContext
Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, context As BlockContext)
MyBase.New(kind, statement, context)
End Sub
Friend Overrides Function Parse() As StatementSyntax
Return Parser.ParseDeclarationStatement()
End Function
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Dim kind As SyntaxKind = node.Kind
Dim methodBlockKind As SyntaxKind
Dim methodBase As MethodBaseSyntax
Select Case kind
Case SyntaxKind.NamespaceStatement
' davidsch - This error check used to be in ParseDeclarations
'In dev10 the error was only on the keyword and not the full statement
Dim reportAnError As Boolean = True
Dim infos As DiagnosticInfo() = node.GetDiagnostics()
If infos IsNot Nothing Then
For Each info In infos
Select Case info.Code
Case ERRID.ERR_NamespaceNotAtNamespace, ERRID.ERR_InvInsideEndsProc
reportAnError = False
Exit For
End Select
Next
End If
If reportAnError Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_NamespaceNotAtNamespace)
End If
Dim context = Me.PrevBlock
RecoverFromMissingEnd(context)
'Let the outer context process this statement
Return context.ProcessSyntax(node)
Case SyntaxKind.ModuleStatement
'In dev10 the error was only on the keyword and not the full statement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ModuleNotAtNamespace)
Return New TypeBlockContext(SyntaxKind.ModuleBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.EnumStatement
Return New EnumDeclarationBlockContext(DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.ClassStatement
Return New TypeBlockContext(SyntaxKind.ClassBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.StructureStatement
Return New TypeBlockContext(SyntaxKind.StructureBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.InterfaceStatement
Return New InterfaceDeclarationBlockContext(DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.SubStatement
methodBlockKind = SyntaxKind.SubBlock
GoTo HandleMethodBase
Case SyntaxKind.SubNewStatement
methodBlockKind = SyntaxKind.ConstructorBlock
GoTo HandleMethodBase
Case SyntaxKind.FunctionStatement
methodBlockKind = SyntaxKind.FunctionBlock
HandleMethodBase:
If Not Parser.IsFirstStatementOnLine(node.GetFirstToken) Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_MethodMustBeFirstStatementOnLine)
End If
' Don't create blocks for MustOverride Sub, Function, and New methods
methodBase = DirectCast(node, MethodBaseSyntax)
If Not methodBase.Modifiers.Any(SyntaxKind.MustOverrideKeyword) Then
Return New MethodBlockContext(methodBlockKind, methodBase, Me)
End If
Add(node)
Case SyntaxKind.OperatorStatement
If Not Parser.IsFirstStatementOnLine(node.GetFirstToken) Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_MethodMustBeFirstStatementOnLine)
End If
' It is a syntax error to have an operator in a module
' This error is reported in declared in Dev10
If Me.BlockKind = SyntaxKind.ModuleBlock Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_OperatorDeclaredInModule)
End If
Return New MethodBlockContext(SyntaxKind.OperatorBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.PropertyStatement
' ===== Make an initial attempt at determining if this might be an auto or expanded property
' We can determine which it is in some cases by looking at the specifiers.
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
Dim modifiers = propertyStatement.Modifiers
Dim isPropertyBlock As Boolean = False
If modifiers.Any Then
If modifiers.Any(SyntaxKind.MustOverrideKeyword) Then
' Mustoverride mean that the property doesn't have any implementation
' This cannot be an auto property so the property may not be initialized.
' Check if initializer exists. Only auto properties may have initialization.
node = PropertyBlockContext.ReportErrorIfHasInitializer(DirectCast(node, PropertyStatementSyntax))
Add(node)
Exit Select
Else
isPropertyBlock = modifiers.Any(SyntaxKind.DefaultKeyword,
SyntaxKind.IteratorKeyword)
End If
End If
Return New PropertyBlockContext(propertyStatement, Me, isPropertyBlock)
Case _
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
'TODO - davidsch - ParseSpecifierDeclaration reports ERRID_ExpectedDeclaration but ParsePropertyOrEventProcedureDefinition reports ERRID_Syntax.
' ERRID_ExpectedDeclaration seems like a better error message.
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExpectedDeclaration)
Add(node)
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
' Per Dev10, build a block event only if all the requirements for one are met,
' i.e. custom modifier and a real AsClause
If eventDecl.CustomKeyword IsNot Nothing Then
If eventDecl.AsClause.AsKeyword.IsMissing Then
' 'Custom' modifier invalid on event declared without an explicit delegate type.
' davidsch - Dev10 put this error on the custom keyword.
node = Parser.ReportSyntaxError(eventDecl, ERRID.ERR_CustomEventRequiresAs)
Else
Return New EventBlockContext(eventDecl, Me)
End If
End If
Add(node)
Case SyntaxKind.AttributesStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_AttributeStmtWrongOrder)
Add(node)
Case SyntaxKind.OptionStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_OptionStmtWrongOrder)
Add(node)
Case SyntaxKind.ImportsStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ImportsMustBeFirst)
Add(node)
Case SyntaxKind.InheritsStatement
Dim beginStatement = Me.BeginStatement
If beginStatement IsNot Nothing AndAlso beginStatement.Kind = SyntaxKind.InterfaceStatement Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_BadInterfaceOrderOnInherits)
Else
node = Parser.ReportSyntaxError(node, ERRID.ERR_InheritsStmtWrongOrder)
End If
Add(node)
Case SyntaxKind.ImplementsStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ImplementsStmtWrongOrder)
Add(node)
Case _
SyntaxKind.EnumBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock
'TODO - Does parser create Constructors? Verify that code was ported correctly.
' Handle any block that can be created by this context
Add(node)
Case _
SyntaxKind.EmptyStatement,
SyntaxKind.IncompleteMember,
SyntaxKind.FieldDeclaration,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.EnumMemberDeclaration
Add(node)
Case SyntaxKind.LabelStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_InvOutsideProc)
Add(node)
Case _
SyntaxKind.EndStatement,
SyntaxKind.StopStatement
' an error has already been reported by ParseGroupEndStatement
Add(node)
Case Else
' Do not report an error on End statements - it is reported on the block begin statement
' or an error that the beginning statement is missing is reported.
If Not SyntaxFacts.IsEndBlockLoopOrNextStatement(node.Kind) Then
Debug.Assert(IsExecutableStatementOrItsPart(node))
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExecutableAsDeclaration)
End If
Add(node)
End Select
Return Me
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
newContext = Nothing
' block-ending statements are always safe to reuse and are very common
If KindEndsBlock(node.Kind) Then
Return UseSyntax(node, newContext)
End If
Select Case node.Kind
Case _
SyntaxKind.NamespaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.EnumStatement,
SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.PropertyStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.EventStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement
Return UseSyntax(node, newContext)
Case _
SyntaxKind.FieldDeclaration,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.EnumMemberDeclaration
Return UseSyntax(node, newContext)
Case _
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock
Return UseSyntax(node, newContext, DirectCast(node, TypeBlockSyntax).EndBlockStatement.IsMissing)
Case SyntaxKind.EnumBlock
Return UseSyntax(node, newContext, DirectCast(node, EnumBlockSyntax).EndEnumStatement.IsMissing)
Case _
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock
Return UseSyntax(node, newContext, DirectCast(node, MethodBlockBaseSyntax).End.IsMissing)
Case SyntaxKind.OperatorBlock
If Me.BlockKind = SyntaxKind.ModuleBlock Then
' Crumble if this is in a module block for correct error processing
newContext = Me
Return LinkResult.Crumble
End If
Return UseSyntax(node, newContext, DirectCast(node, OperatorBlockSyntax).End.IsMissing)
Case SyntaxKind.EventBlock
Return UseSyntax(node, newContext, DirectCast(node, EventBlockSyntax).EndEventStatement.IsMissing)
Case SyntaxKind.PropertyBlock
Return UseSyntax(node, newContext, DirectCast(node, PropertyBlockSyntax).EndPropertyStatement.IsMissing)
Case _
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleBlock
' Crumble to handle errors for NamespaceBlock and ModuleBlock.
newContext = Me
Return LinkResult.Crumble
' single line If gets parsed as unexpected If + some garbage
' when in declaration context so cannot be reused
' see bug 901645
Case SyntaxKind.SingleLineIfStatement
newContext = Me
Return LinkResult.Crumble
Case SyntaxKind.LocalDeclarationStatement
' Crumble so they become field declarations
newContext = Me
Return LinkResult.Crumble
' TODO: need to add all executable statements that ParseDeclarationStatement handle as unexpected executables
' Move error reporting from ParseDeclarationStatement to the context.
Case SyntaxKind.IfStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExecutableAsDeclaration)
Return TryUseStatement(node, newContext)
' by default statements are not handled in declaration context
Case Else
newContext = Me
Return LinkResult.NotUsed
End Select
End Function
Friend Overrides Function RecoverFromMismatchedEnd(statement As StatementSyntax) As BlockContext
Debug.Assert(statement IsNot Nothing)
' // The end construct is extraneous. Report an error and leave
' // the current context alone.
Dim ErrorId As ERRID = ERRID.ERR_Syntax
Dim stmtKind = statement.Kind
Select Case (stmtKind)
Case SyntaxKind.EndIfStatement
ErrorId = ERRID.ERR_EndIfNoMatchingIf
Case SyntaxKind.EndWithStatement
ErrorId = ERRID.ERR_EndWithWithoutWith
Case SyntaxKind.EndSelectStatement
ErrorId = ERRID.ERR_EndSelectNoSelect
Case SyntaxKind.EndWhileStatement
ErrorId = ERRID.ERR_EndWhileNoWhile
Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement
ErrorId = ERRID.ERR_LoopNoMatchingDo
Case SyntaxKind.NextStatement
ErrorId = ERRID.ERR_NextNoMatchingFor
Case SyntaxKind.EndSubStatement
ErrorId = ERRID.ERR_InvalidEndSub
Case SyntaxKind.EndFunctionStatement
ErrorId = ERRID.ERR_InvalidEndFunction
Case SyntaxKind.EndOperatorStatement
ErrorId = ERRID.ERR_InvalidEndOperator
Case SyntaxKind.EndPropertyStatement
ErrorId = ERRID.ERR_InvalidEndProperty
Case SyntaxKind.EndGetStatement
ErrorId = ERRID.ERR_InvalidEndGet
Case SyntaxKind.EndSetStatement
ErrorId = ERRID.ERR_InvalidEndSet
Case SyntaxKind.EndEventStatement
ErrorId = ERRID.ERR_InvalidEndEvent
Case SyntaxKind.EndAddHandlerStatement
ErrorId = ERRID.ERR_InvalidEndAddHandler
Case SyntaxKind.EndRemoveHandlerStatement
ErrorId = ERRID.ERR_InvalidEndRemoveHandler
Case SyntaxKind.EndRaiseEventStatement
ErrorId = ERRID.ERR_InvalidEndRaiseEvent
Case SyntaxKind.EndStructureStatement
ErrorId = ERRID.ERR_EndStructureNoStructure
Case SyntaxKind.EndEnumStatement
ErrorId = ERRID.ERR_InvalidEndEnum
Case SyntaxKind.EndInterfaceStatement
ErrorId = ERRID.ERR_InvalidEndInterface
Case SyntaxKind.EndTryStatement
ErrorId = ERRID.ERR_EndTryNoTry
Case SyntaxKind.EndClassStatement
ErrorId = ERRID.ERR_EndClassNoClass
Case SyntaxKind.EndModuleStatement
ErrorId = ERRID.ERR_EndModuleNoModule
Case SyntaxKind.EndNamespaceStatement
ErrorId = ERRID.ERR_EndNamespaceNoNamespace
Case SyntaxKind.EndUsingStatement
ErrorId = ERRID.ERR_EndUsingWithoutUsing
Case SyntaxKind.EndSyncLockStatement
ErrorId = ERRID.ERR_EndSyncLockNoSyncLock
#If UNDONE Then
'TODO - davidsch - handle regions
Case NodeKind.EndRegionStatement
ErrorId = ERRID.ERR_EndRegionNoRegion
#End If
Case SyntaxKind.EmptyStatement, SyntaxKind.IncompleteMember
ErrorId = ERRID.ERR_UnrecognizedEnd
Case Else
Throw New ArgumentException("Statement must be an end block statement")
End Select
'TODO
' Should ReportSyntaxError be on the Parser or can it be made static
' If the parser isn't needed for more than this then remove it from the context.
statement = Parser.ReportSyntaxError(statement, ErrorId)
Return ProcessSyntax(statement)
End Function
Friend Overrides Function EndBlock(endStmt As StatementSyntax) As BlockContext
Dim blockSyntax = CreateBlockSyntax(endStmt)
Dim context = PrevBlock.ProcessSyntax(blockSyntax)
Return context
End Function
Friend Overrides Function ProcessStatementTerminator(lambdaContext As BlockContext) As BlockContext
Parser.ConsumeStatementTerminator(colonAsSeparator:=False)
Return Me
End Function
Friend Overrides ReadOnly Property IsSingleLine As Boolean
Get
Return False
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend MustInherit Class DeclarationContext
Inherits BlockContext
Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, context As BlockContext)
MyBase.New(kind, statement, context)
End Sub
Friend Overrides Function Parse() As StatementSyntax
Return Parser.ParseDeclarationStatement()
End Function
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Dim kind As SyntaxKind = node.Kind
Dim methodBlockKind As SyntaxKind
Dim methodBase As MethodBaseSyntax
Select Case kind
Case SyntaxKind.NamespaceStatement
' davidsch - This error check used to be in ParseDeclarations
'In dev10 the error was only on the keyword and not the full statement
Dim reportAnError As Boolean = True
Dim infos As DiagnosticInfo() = node.GetDiagnostics()
If infos IsNot Nothing Then
For Each info In infos
Select Case info.Code
Case ERRID.ERR_NamespaceNotAtNamespace, ERRID.ERR_InvInsideEndsProc
reportAnError = False
Exit For
End Select
Next
End If
If reportAnError Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_NamespaceNotAtNamespace)
End If
Dim context = Me.PrevBlock
RecoverFromMissingEnd(context)
'Let the outer context process this statement
Return context.ProcessSyntax(node)
Case SyntaxKind.ModuleStatement
'In dev10 the error was only on the keyword and not the full statement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ModuleNotAtNamespace)
Return New TypeBlockContext(SyntaxKind.ModuleBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.EnumStatement
Return New EnumDeclarationBlockContext(DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.ClassStatement
Return New TypeBlockContext(SyntaxKind.ClassBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.StructureStatement
Return New TypeBlockContext(SyntaxKind.StructureBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.InterfaceStatement
Return New InterfaceDeclarationBlockContext(DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.SubStatement
methodBlockKind = SyntaxKind.SubBlock
GoTo HandleMethodBase
Case SyntaxKind.SubNewStatement
methodBlockKind = SyntaxKind.ConstructorBlock
GoTo HandleMethodBase
Case SyntaxKind.FunctionStatement
methodBlockKind = SyntaxKind.FunctionBlock
HandleMethodBase:
If Not Parser.IsFirstStatementOnLine(node.GetFirstToken) Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_MethodMustBeFirstStatementOnLine)
End If
' Don't create blocks for MustOverride Sub, Function, and New methods
methodBase = DirectCast(node, MethodBaseSyntax)
If Not methodBase.Modifiers.Any(SyntaxKind.MustOverrideKeyword) Then
Return New MethodBlockContext(methodBlockKind, methodBase, Me)
End If
Add(node)
Case SyntaxKind.OperatorStatement
If Not Parser.IsFirstStatementOnLine(node.GetFirstToken) Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_MethodMustBeFirstStatementOnLine)
End If
' It is a syntax error to have an operator in a module
' This error is reported in declared in Dev10
If Me.BlockKind = SyntaxKind.ModuleBlock Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_OperatorDeclaredInModule)
End If
Return New MethodBlockContext(SyntaxKind.OperatorBlock, DirectCast(node, StatementSyntax), Me)
Case SyntaxKind.PropertyStatement
' ===== Make an initial attempt at determining if this might be an auto or expanded property
' We can determine which it is in some cases by looking at the specifiers.
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
Dim modifiers = propertyStatement.Modifiers
Dim isPropertyBlock As Boolean = False
If modifiers.Any Then
If modifiers.Any(SyntaxKind.MustOverrideKeyword) Then
' Mustoverride mean that the property doesn't have any implementation
' This cannot be an auto property so the property may not be initialized.
' Check if initializer exists. Only auto properties may have initialization.
node = PropertyBlockContext.ReportErrorIfHasInitializer(DirectCast(node, PropertyStatementSyntax))
Add(node)
Exit Select
Else
isPropertyBlock = modifiers.Any(SyntaxKind.DefaultKeyword,
SyntaxKind.IteratorKeyword)
End If
End If
Return New PropertyBlockContext(propertyStatement, Me, isPropertyBlock)
Case _
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
'TODO - davidsch - ParseSpecifierDeclaration reports ERRID_ExpectedDeclaration but ParsePropertyOrEventProcedureDefinition reports ERRID_Syntax.
' ERRID_ExpectedDeclaration seems like a better error message.
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExpectedDeclaration)
Add(node)
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
' Per Dev10, build a block event only if all the requirements for one are met,
' i.e. custom modifier and a real AsClause
If eventDecl.CustomKeyword IsNot Nothing Then
If eventDecl.AsClause.AsKeyword.IsMissing Then
' 'Custom' modifier invalid on event declared without an explicit delegate type.
' davidsch - Dev10 put this error on the custom keyword.
node = Parser.ReportSyntaxError(eventDecl, ERRID.ERR_CustomEventRequiresAs)
Else
Return New EventBlockContext(eventDecl, Me)
End If
End If
Add(node)
Case SyntaxKind.AttributesStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_AttributeStmtWrongOrder)
Add(node)
Case SyntaxKind.OptionStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_OptionStmtWrongOrder)
Add(node)
Case SyntaxKind.ImportsStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ImportsMustBeFirst)
Add(node)
Case SyntaxKind.InheritsStatement
Dim beginStatement = Me.BeginStatement
If beginStatement IsNot Nothing AndAlso beginStatement.Kind = SyntaxKind.InterfaceStatement Then
node = Parser.ReportSyntaxError(node, ERRID.ERR_BadInterfaceOrderOnInherits)
Else
node = Parser.ReportSyntaxError(node, ERRID.ERR_InheritsStmtWrongOrder)
End If
Add(node)
Case SyntaxKind.ImplementsStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ImplementsStmtWrongOrder)
Add(node)
Case _
SyntaxKind.EnumBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock
'TODO - Does parser create Constructors? Verify that code was ported correctly.
' Handle any block that can be created by this context
Add(node)
Case _
SyntaxKind.EmptyStatement,
SyntaxKind.IncompleteMember,
SyntaxKind.FieldDeclaration,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.EnumMemberDeclaration
Add(node)
Case SyntaxKind.LabelStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_InvOutsideProc)
Add(node)
Case _
SyntaxKind.EndStatement,
SyntaxKind.StopStatement
' an error has already been reported by ParseGroupEndStatement
Add(node)
Case Else
' Do not report an error on End statements - it is reported on the block begin statement
' or an error that the beginning statement is missing is reported.
If Not SyntaxFacts.IsEndBlockLoopOrNextStatement(node.Kind) Then
Debug.Assert(IsExecutableStatementOrItsPart(node))
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExecutableAsDeclaration)
End If
Add(node)
End Select
Return Me
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
newContext = Nothing
' block-ending statements are always safe to reuse and are very common
If KindEndsBlock(node.Kind) Then
Return UseSyntax(node, newContext)
End If
Select Case node.Kind
Case _
SyntaxKind.NamespaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.EnumStatement,
SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.PropertyStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.EventStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement
Return UseSyntax(node, newContext)
Case _
SyntaxKind.FieldDeclaration,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.EnumMemberDeclaration
Return UseSyntax(node, newContext)
Case _
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock
Return UseSyntax(node, newContext, DirectCast(node, TypeBlockSyntax).EndBlockStatement.IsMissing)
Case SyntaxKind.EnumBlock
Return UseSyntax(node, newContext, DirectCast(node, EnumBlockSyntax).EndEnumStatement.IsMissing)
Case _
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock
Return UseSyntax(node, newContext, DirectCast(node, MethodBlockBaseSyntax).End.IsMissing)
Case SyntaxKind.OperatorBlock
If Me.BlockKind = SyntaxKind.ModuleBlock Then
' Crumble if this is in a module block for correct error processing
newContext = Me
Return LinkResult.Crumble
End If
Return UseSyntax(node, newContext, DirectCast(node, OperatorBlockSyntax).End.IsMissing)
Case SyntaxKind.EventBlock
Return UseSyntax(node, newContext, DirectCast(node, EventBlockSyntax).EndEventStatement.IsMissing)
Case SyntaxKind.PropertyBlock
Return UseSyntax(node, newContext, DirectCast(node, PropertyBlockSyntax).EndPropertyStatement.IsMissing)
Case _
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleBlock
' Crumble to handle errors for NamespaceBlock and ModuleBlock.
newContext = Me
Return LinkResult.Crumble
' single line If gets parsed as unexpected If + some garbage
' when in declaration context so cannot be reused
' see bug 901645
Case SyntaxKind.SingleLineIfStatement
newContext = Me
Return LinkResult.Crumble
Case SyntaxKind.LocalDeclarationStatement
' Crumble so they become field declarations
newContext = Me
Return LinkResult.Crumble
' TODO: need to add all executable statements that ParseDeclarationStatement handle as unexpected executables
' Move error reporting from ParseDeclarationStatement to the context.
Case SyntaxKind.IfStatement
node = Parser.ReportSyntaxError(node, ERRID.ERR_ExecutableAsDeclaration)
Return TryUseStatement(node, newContext)
' by default statements are not handled in declaration context
Case Else
newContext = Me
Return LinkResult.NotUsed
End Select
End Function
Friend Overrides Function RecoverFromMismatchedEnd(statement As StatementSyntax) As BlockContext
Debug.Assert(statement IsNot Nothing)
' // The end construct is extraneous. Report an error and leave
' // the current context alone.
Dim ErrorId As ERRID = ERRID.ERR_Syntax
Dim stmtKind = statement.Kind
Select Case (stmtKind)
Case SyntaxKind.EndIfStatement
ErrorId = ERRID.ERR_EndIfNoMatchingIf
Case SyntaxKind.EndWithStatement
ErrorId = ERRID.ERR_EndWithWithoutWith
Case SyntaxKind.EndSelectStatement
ErrorId = ERRID.ERR_EndSelectNoSelect
Case SyntaxKind.EndWhileStatement
ErrorId = ERRID.ERR_EndWhileNoWhile
Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement
ErrorId = ERRID.ERR_LoopNoMatchingDo
Case SyntaxKind.NextStatement
ErrorId = ERRID.ERR_NextNoMatchingFor
Case SyntaxKind.EndSubStatement
ErrorId = ERRID.ERR_InvalidEndSub
Case SyntaxKind.EndFunctionStatement
ErrorId = ERRID.ERR_InvalidEndFunction
Case SyntaxKind.EndOperatorStatement
ErrorId = ERRID.ERR_InvalidEndOperator
Case SyntaxKind.EndPropertyStatement
ErrorId = ERRID.ERR_InvalidEndProperty
Case SyntaxKind.EndGetStatement
ErrorId = ERRID.ERR_InvalidEndGet
Case SyntaxKind.EndSetStatement
ErrorId = ERRID.ERR_InvalidEndSet
Case SyntaxKind.EndEventStatement
ErrorId = ERRID.ERR_InvalidEndEvent
Case SyntaxKind.EndAddHandlerStatement
ErrorId = ERRID.ERR_InvalidEndAddHandler
Case SyntaxKind.EndRemoveHandlerStatement
ErrorId = ERRID.ERR_InvalidEndRemoveHandler
Case SyntaxKind.EndRaiseEventStatement
ErrorId = ERRID.ERR_InvalidEndRaiseEvent
Case SyntaxKind.EndStructureStatement
ErrorId = ERRID.ERR_EndStructureNoStructure
Case SyntaxKind.EndEnumStatement
ErrorId = ERRID.ERR_InvalidEndEnum
Case SyntaxKind.EndInterfaceStatement
ErrorId = ERRID.ERR_InvalidEndInterface
Case SyntaxKind.EndTryStatement
ErrorId = ERRID.ERR_EndTryNoTry
Case SyntaxKind.EndClassStatement
ErrorId = ERRID.ERR_EndClassNoClass
Case SyntaxKind.EndModuleStatement
ErrorId = ERRID.ERR_EndModuleNoModule
Case SyntaxKind.EndNamespaceStatement
ErrorId = ERRID.ERR_EndNamespaceNoNamespace
Case SyntaxKind.EndUsingStatement
ErrorId = ERRID.ERR_EndUsingWithoutUsing
Case SyntaxKind.EndSyncLockStatement
ErrorId = ERRID.ERR_EndSyncLockNoSyncLock
#If UNDONE Then
'TODO - davidsch - handle regions
Case NodeKind.EndRegionStatement
ErrorId = ERRID.ERR_EndRegionNoRegion
#End If
Case SyntaxKind.EmptyStatement, SyntaxKind.IncompleteMember
ErrorId = ERRID.ERR_UnrecognizedEnd
Case Else
Throw New ArgumentException("Statement must be an end block statement")
End Select
'TODO
' Should ReportSyntaxError be on the Parser or can it be made static
' If the parser isn't needed for more than this then remove it from the context.
statement = Parser.ReportSyntaxError(statement, ErrorId)
Return ProcessSyntax(statement)
End Function
Friend Overrides Function EndBlock(endStmt As StatementSyntax) As BlockContext
Dim blockSyntax = CreateBlockSyntax(endStmt)
Dim context = PrevBlock.ProcessSyntax(blockSyntax)
Return context
End Function
Friend Overrides Function ProcessStatementTerminator(lambdaContext As BlockContext) As BlockContext
Parser.ConsumeStatementTerminator(colonAsSeparator:=False)
Return Me
End Function
Friend Overrides ReadOnly Property IsSingleLine As Boolean
Get
Return False
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/InterpolatedStringBuilderLocalSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A synthesized local variable with a val escape scope.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal sealed class SynthesizedLocalWithValEscape : SynthesizedLocal
{
public SynthesizedLocalWithValEscape(
MethodSymbol? containingMethod,
TypeWithAnnotations typeWithAnnotations,
SynthesizedLocalKind kind,
uint valEscapeScope,
SyntaxNode? syntaxOpt = null,
bool isPinned = false,
RefKind refKind = RefKind.None
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string? createdAtFilePath = null
#endif
) : base(containingMethod, typeWithAnnotations, kind, syntaxOpt, isPinned, refKind
#if DEBUG
, createdAtLineNumber, createdAtFilePath
#endif
)
{
ValEscapeScope = valEscapeScope;
}
internal override uint ValEscapeScope { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A synthesized local variable with a val escape scope.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal sealed class SynthesizedLocalWithValEscape : SynthesizedLocal
{
public SynthesizedLocalWithValEscape(
MethodSymbol? containingMethod,
TypeWithAnnotations typeWithAnnotations,
SynthesizedLocalKind kind,
uint valEscapeScope,
SyntaxNode? syntaxOpt = null,
bool isPinned = false,
RefKind refKind = RefKind.None
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string? createdAtFilePath = null
#endif
) : base(containingMethod, typeWithAnnotations, kind, syntaxOpt, isPinned, refKind
#if DEBUG
, createdAtLineNumber, createdAtFilePath
#endif
)
{
ValEscapeScope = valEscapeScope;
}
internal override uint ValEscapeScope { get; }
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.TypeNames.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.ObjectModel
Imports System.Runtime.InteropServices
Imports System.Text
Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
' Implementation for "displaying type name as string" aspect of Visual Basic Formatter component
Partial Friend NotInheritable Class VisualBasicFormatter
Private Shared Function IsPotentialKeyword(identifier As String) As Boolean
Return SyntaxFacts.GetKeywordKind(identifier) <> SyntaxKind.None OrElse SyntaxFacts.GetContextualKeywordKind(identifier) <> SyntaxKind.None
End Function
Protected Overrides Sub AppendIdentifierEscapingPotentialKeywords(builder As StringBuilder, identifier As String, <Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = Not IsValidIdentifier(identifier)
If IsPotentialKeyword(identifier) Then
builder.Append("["c)
builder.Append(identifier)
builder.Append("]"c)
Else
builder.Append(identifier)
End If
End Sub
Protected Overrides Sub AppendGenericTypeArguments(
builder As StringBuilder,
typeArguments() As Type,
typeArgumentOffset As Integer,
dynamicFlags As ReadOnlyCollection(Of Byte),
ByRef dynamicFlagIndex As Integer,
tupleElementNames As ReadOnlyCollection(Of String),
ByRef tupleElementIndex As Integer,
arity As Integer,
escapeKeywordIdentifiers As Boolean,
<Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = False
builder.Append("(Of ")
For i = 0 To arity - 1
If i > 0 Then
builder.Append(", ")
End If
Dim sawSingleInvalidIdentifier = False
Dim typeArgument As Type = typeArguments(typeArgumentOffset + i)
AppendQualifiedTypeName(
builder,
typeArgument,
dynamicFlags,
dynamicFlagIndex,
tupleElementNames,
tupleElementIndex,
escapeKeywordIdentifiers,
sawSingleInvalidIdentifier)
sawInvalidIdentifier = sawInvalidIdentifier Or sawSingleInvalidIdentifier
Next
builder.Append(")"c)
End Sub
Protected Overrides Sub AppendTupleElement(
builder As StringBuilder,
type As Type,
nameOpt As String,
dynamicFlags As ReadOnlyCollection(Of Byte),
ByRef dynamicFlagIndex As Integer,
tupleElementNames As ReadOnlyCollection(Of String),
ByRef tupleElementIndex As Integer,
escapeKeywordIdentifiers As Boolean,
<Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = False
Dim sawSingleInvalidIdentifier = False
If Not String.IsNullOrEmpty(nameOpt) Then
AppendIdentifier(builder, escapeKeywordIdentifiers, nameOpt, sawSingleInvalidIdentifier)
sawInvalidIdentifier = sawInvalidIdentifier Or sawSingleInvalidIdentifier
builder.Append(" As ")
End If
AppendQualifiedTypeName(
builder,
type,
dynamicFlags,
dynamicFlagIndex,
tupleElementNames,
tupleElementIndex,
escapeKeywordIdentifiers,
sawSingleInvalidIdentifier)
Debug.Assert(Not sawSingleInvalidIdentifier)
End Sub
Protected Overrides Sub AppendRankSpecifier(builder As StringBuilder, rank As Integer)
Debug.Assert(rank > 0)
builder.Append("("c)
builder.Append(","c, rank - 1)
builder.Append(")"c)
End Sub
Protected Overrides Function AppendSpecialTypeName(builder As StringBuilder, type As Type, isDynamic As Boolean) As Boolean
' NOTE: isDynamic is ignored in VB.
If type.IsPredefinedType() Then
builder.Append(type.GetPredefinedTypeName()) ' Not an identifier, does not require escaping.
Return True
End If
Return False
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.ObjectModel
Imports System.Runtime.InteropServices
Imports System.Text
Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
' Implementation for "displaying type name as string" aspect of Visual Basic Formatter component
Partial Friend NotInheritable Class VisualBasicFormatter
Private Shared Function IsPotentialKeyword(identifier As String) As Boolean
Return SyntaxFacts.GetKeywordKind(identifier) <> SyntaxKind.None OrElse SyntaxFacts.GetContextualKeywordKind(identifier) <> SyntaxKind.None
End Function
Protected Overrides Sub AppendIdentifierEscapingPotentialKeywords(builder As StringBuilder, identifier As String, <Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = Not IsValidIdentifier(identifier)
If IsPotentialKeyword(identifier) Then
builder.Append("["c)
builder.Append(identifier)
builder.Append("]"c)
Else
builder.Append(identifier)
End If
End Sub
Protected Overrides Sub AppendGenericTypeArguments(
builder As StringBuilder,
typeArguments() As Type,
typeArgumentOffset As Integer,
dynamicFlags As ReadOnlyCollection(Of Byte),
ByRef dynamicFlagIndex As Integer,
tupleElementNames As ReadOnlyCollection(Of String),
ByRef tupleElementIndex As Integer,
arity As Integer,
escapeKeywordIdentifiers As Boolean,
<Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = False
builder.Append("(Of ")
For i = 0 To arity - 1
If i > 0 Then
builder.Append(", ")
End If
Dim sawSingleInvalidIdentifier = False
Dim typeArgument As Type = typeArguments(typeArgumentOffset + i)
AppendQualifiedTypeName(
builder,
typeArgument,
dynamicFlags,
dynamicFlagIndex,
tupleElementNames,
tupleElementIndex,
escapeKeywordIdentifiers,
sawSingleInvalidIdentifier)
sawInvalidIdentifier = sawInvalidIdentifier Or sawSingleInvalidIdentifier
Next
builder.Append(")"c)
End Sub
Protected Overrides Sub AppendTupleElement(
builder As StringBuilder,
type As Type,
nameOpt As String,
dynamicFlags As ReadOnlyCollection(Of Byte),
ByRef dynamicFlagIndex As Integer,
tupleElementNames As ReadOnlyCollection(Of String),
ByRef tupleElementIndex As Integer,
escapeKeywordIdentifiers As Boolean,
<Out> ByRef sawInvalidIdentifier As Boolean)
sawInvalidIdentifier = False
Dim sawSingleInvalidIdentifier = False
If Not String.IsNullOrEmpty(nameOpt) Then
AppendIdentifier(builder, escapeKeywordIdentifiers, nameOpt, sawSingleInvalidIdentifier)
sawInvalidIdentifier = sawInvalidIdentifier Or sawSingleInvalidIdentifier
builder.Append(" As ")
End If
AppendQualifiedTypeName(
builder,
type,
dynamicFlags,
dynamicFlagIndex,
tupleElementNames,
tupleElementIndex,
escapeKeywordIdentifiers,
sawSingleInvalidIdentifier)
Debug.Assert(Not sawSingleInvalidIdentifier)
End Sub
Protected Overrides Sub AppendRankSpecifier(builder As StringBuilder, rank As Integer)
Debug.Assert(rank > 0)
builder.Append("("c)
builder.Append(","c, rank - 1)
builder.Append(")"c)
End Sub
Protected Overrides Function AppendSpecialTypeName(builder As StringBuilder, type As Type, isDynamic As Boolean) As Boolean
' NOTE: isDynamic is ignored in VB.
If type.IsPredefinedType() Then
builder.Append(type.GetPredefinedTypeName()) ' Not an identifier, does not require escaping.
Return True
End If
Return False
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Dependencies/Collections/Internal/HashHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal static class HashHelpers
{
// This is the maximum prime smaller than Array.MaxArrayLength
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
public const int HashPrime = 101;
// Table of prime numbers to use as hash table sizes.
// A typical resize algorithm would pick the smallest prime number in this array
// that is larger than twice the previous capacity.
// Suppose our Hashtable currently has capacity x and enough elements are added
// such that a resize needs to occur. Resizing first computes 2x then finds the
// first prime in the table greater than 2x, i.e. if primes are ordered
// p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n.
// Doubling is important for preserving the asymptotic complexity of the
// hashtable operations such as add. Having a prime guarantees that double
// hashing does not lead to infinite loops. IE, your hash function will be
// h1(key) + i*h2(key), 0 <= i < size. h2 and the size must be relatively prime.
// We prefer the low computation costs of higher prime numbers over the increased
// memory allocation of a fixed prime number i.e. when right sizing a HashSet.
private static readonly int[] s_primes =
{
3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369
};
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
var limit = (int)Math.Sqrt(candidate);
for (var divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return candidate == 2;
}
public static int GetPrime(int min)
{
if (min < 0)
throw new ArgumentException(SR.Arg_HTCapacityOverflow);
foreach (var prime in s_primes)
{
if (prime >= min)
return prime;
}
// Outside of our predefined table. Compute the hard way.
for (var i = (min | 1); i < int.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HashPrime != 0))
return i;
}
return min;
}
// Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
var newSize = 2 * oldSize;
// Allow the hashtables to grow to maximum possible size (~2G elements) before encountering capacity overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
Debug.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
return GetPrime(newSize);
}
/// <summary>Returns approximate reciprocal of the divisor: ceil(2**64 / divisor).</summary>
/// <remarks>This should only be used on 64-bit.</remarks>
public static ulong GetFastModMultiplier(uint divisor) =>
ulong.MaxValue / divisor + 1;
/// <summary>Performs a mod operation using the multiplier pre-computed with <see cref="GetFastModMultiplier"/>.</summary>
/// <remarks>
/// PERF: This improves performance in 64-bit scenarios at the expense of performance in 32-bit scenarios. Since
/// we only build a single AnyCPU binary, we opt for improved performance in the 64-bit scenario.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint FastMod(uint value, uint divisor, ulong multiplier)
{
// We use modified Daniel Lemire's fastmod algorithm (https://github.com/dotnet/runtime/pull/406),
// which allows to avoid the long multiplication if the divisor is less than 2**31.
Debug.Assert(divisor <= int.MaxValue);
// This is equivalent of (uint)Math.BigMul(multiplier * value, divisor, out _). This version
// is faster than BigMul currently because we only need the high bits.
var highbits = (uint)(((((multiplier * value) >> 32) + 1) * divisor) >> 32);
Debug.Assert(highbits == value % divisor);
return highbits;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal static class HashHelpers
{
// This is the maximum prime smaller than Array.MaxArrayLength
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
public const int HashPrime = 101;
// Table of prime numbers to use as hash table sizes.
// A typical resize algorithm would pick the smallest prime number in this array
// that is larger than twice the previous capacity.
// Suppose our Hashtable currently has capacity x and enough elements are added
// such that a resize needs to occur. Resizing first computes 2x then finds the
// first prime in the table greater than 2x, i.e. if primes are ordered
// p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n.
// Doubling is important for preserving the asymptotic complexity of the
// hashtable operations such as add. Having a prime guarantees that double
// hashing does not lead to infinite loops. IE, your hash function will be
// h1(key) + i*h2(key), 0 <= i < size. h2 and the size must be relatively prime.
// We prefer the low computation costs of higher prime numbers over the increased
// memory allocation of a fixed prime number i.e. when right sizing a HashSet.
private static readonly int[] s_primes =
{
3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369
};
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
var limit = (int)Math.Sqrt(candidate);
for (var divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return candidate == 2;
}
public static int GetPrime(int min)
{
if (min < 0)
throw new ArgumentException(SR.Arg_HTCapacityOverflow);
foreach (var prime in s_primes)
{
if (prime >= min)
return prime;
}
// Outside of our predefined table. Compute the hard way.
for (var i = (min | 1); i < int.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HashPrime != 0))
return i;
}
return min;
}
// Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
var newSize = 2 * oldSize;
// Allow the hashtables to grow to maximum possible size (~2G elements) before encountering capacity overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
Debug.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
return GetPrime(newSize);
}
/// <summary>Returns approximate reciprocal of the divisor: ceil(2**64 / divisor).</summary>
/// <remarks>This should only be used on 64-bit.</remarks>
public static ulong GetFastModMultiplier(uint divisor) =>
ulong.MaxValue / divisor + 1;
/// <summary>Performs a mod operation using the multiplier pre-computed with <see cref="GetFastModMultiplier"/>.</summary>
/// <remarks>
/// PERF: This improves performance in 64-bit scenarios at the expense of performance in 32-bit scenarios. Since
/// we only build a single AnyCPU binary, we opt for improved performance in the 64-bit scenario.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint FastMod(uint value, uint divisor, ulong multiplier)
{
// We use modified Daniel Lemire's fastmod algorithm (https://github.com/dotnet/runtime/pull/406),
// which allows to avoid the long multiplication if the divisor is less than 2**31.
Debug.Assert(divisor <= int.MaxValue);
// This is equivalent of (uint)Math.BigMul(multiplier * value, divisor, out _). This version
// is faster than BigMul currently because we only need the high bits.
var highbits = (uint)(((((multiplier * value) >> 32) + 1) * divisor) >> 32);
Debug.Assert(highbits == value % divisor);
return highbits;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxNodeOrTokenListTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class SyntaxNodeOrTokenListTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var node1 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("a"));
var node2 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("b"));
EqualityTesting.AssertEqual(default(SeparatedSyntaxList<CSharpSyntaxNode>), default(SeparatedSyntaxList<CSharpSyntaxNode>));
EqualityTesting.AssertEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node1, 0));
EqualityTesting.AssertEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node1, 1));
EqualityTesting.AssertNotEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node2, 0));
}
[Fact]
public void EnumeratorEquality()
{
Assert.Throws<NotSupportedException>(() => default(SyntaxNodeOrTokenList.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxNodeOrTokenList.Enumerator).Equals(default(SyntaxNodeOrTokenList.Enumerator)));
}
[Fact]
public void TestAddInsertRemove()
{
var list = SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C "));
Assert.Equal(3, list.Count);
Assert.Equal("A", list[0].ToString());
Assert.Equal("B", list[1].ToString());
Assert.Equal("C", list[2].ToString());
Assert.Equal("A B C ", list.ToFullString());
var elementA = list[0];
var elementB = list[1];
var elementC = list[2];
Assert.Equal(0, list.IndexOf(elementA));
Assert.Equal(1, list.IndexOf(elementB));
Assert.Equal(2, list.IndexOf(elementC));
SyntaxNodeOrToken tokenD = SyntaxFactory.ParseToken("D ");
SyntaxNodeOrToken nameE = SyntaxFactory.ParseExpression("E ");
var newList = list.Add(tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("D A B C ", newList.ToFullString());
newList = list.Insert(1, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A D B C ", newList.ToFullString());
newList = list.Insert(2, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B D C ", newList.ToFullString());
newList = list.Insert(3, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("D E A B C ", newList.ToFullString());
newList = list.InsertRange(1, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A D E B C ", newList.ToFullString());
newList = list.InsertRange(2, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B D E C ", newList.ToFullString());
newList = list.InsertRange(3, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.RemoveAt(0);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.RemoveAt(list.Count - 1);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Remove(elementA);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.Remove(elementB);
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.Remove(elementC);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Replace(elementA, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("D B C ", newList.ToFullString());
newList = list.Replace(elementB, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A D C ", newList.ToFullString());
newList = list.Replace(elementC, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A B D ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("D E B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("A D E C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("A B D E ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, nameE));
Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { nameE }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxNodeOrToken>)null));
}
[Fact]
public void TestAddInsertRemoveReplaceOnEmptyList()
{
DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.NodeOrTokenList());
DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxNodeOrTokenList));
}
private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxNodeOrTokenList list)
{
Assert.Equal(0, list.Count);
SyntaxNodeOrToken tokenD = SyntaxFactory.ParseToken("D ");
SyntaxNodeOrToken nodeE = SyntaxFactory.ParseExpression("E ");
var newList = list.Add(tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, nodeE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, nodeE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Remove(tokenD);
Assert.Equal(0, newList.Count);
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNodeOrToken>)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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class SyntaxNodeOrTokenListTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var node1 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("a"));
var node2 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("b"));
EqualityTesting.AssertEqual(default(SeparatedSyntaxList<CSharpSyntaxNode>), default(SeparatedSyntaxList<CSharpSyntaxNode>));
EqualityTesting.AssertEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node1, 0));
EqualityTesting.AssertEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node1, 1));
EqualityTesting.AssertNotEqual(new SyntaxNodeOrTokenList(node1, 0), new SyntaxNodeOrTokenList(node2, 0));
}
[Fact]
public void EnumeratorEquality()
{
Assert.Throws<NotSupportedException>(() => default(SyntaxNodeOrTokenList.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxNodeOrTokenList.Enumerator).Equals(default(SyntaxNodeOrTokenList.Enumerator)));
}
[Fact]
public void TestAddInsertRemove()
{
var list = SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C "));
Assert.Equal(3, list.Count);
Assert.Equal("A", list[0].ToString());
Assert.Equal("B", list[1].ToString());
Assert.Equal("C", list[2].ToString());
Assert.Equal("A B C ", list.ToFullString());
var elementA = list[0];
var elementB = list[1];
var elementC = list[2];
Assert.Equal(0, list.IndexOf(elementA));
Assert.Equal(1, list.IndexOf(elementB));
Assert.Equal(2, list.IndexOf(elementC));
SyntaxNodeOrToken tokenD = SyntaxFactory.ParseToken("D ");
SyntaxNodeOrToken nameE = SyntaxFactory.ParseExpression("E ");
var newList = list.Add(tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("D A B C ", newList.ToFullString());
newList = list.Insert(1, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A D B C ", newList.ToFullString());
newList = list.Insert(2, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B D C ", newList.ToFullString());
newList = list.Insert(3, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("D E A B C ", newList.ToFullString());
newList = list.InsertRange(1, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A D E B C ", newList.ToFullString());
newList = list.InsertRange(2, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B D E C ", newList.ToFullString());
newList = list.InsertRange(3, new[] { tokenD, nameE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.RemoveAt(0);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.RemoveAt(list.Count - 1);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Remove(elementA);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.Remove(elementB);
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.Remove(elementC);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Replace(elementA, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("D B C ", newList.ToFullString());
newList = list.Replace(elementB, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A D C ", newList.ToFullString());
newList = list.Replace(elementC, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A B D ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("D E B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("A D E C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new[] { tokenD, nameE });
Assert.Equal(4, newList.Count);
Assert.Equal("A B D E ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new SyntaxNodeOrToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, nameE));
Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { nameE }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxNodeOrToken>)null));
}
[Fact]
public void TestAddInsertRemoveReplaceOnEmptyList()
{
DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.NodeOrTokenList());
DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxNodeOrTokenList));
}
private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxNodeOrTokenList list)
{
Assert.Equal(0, list.Count);
SyntaxNodeOrToken tokenD = SyntaxFactory.ParseToken("D ");
SyntaxNodeOrToken nodeE = SyntaxFactory.ParseExpression("E ");
var newList = list.Add(tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, nodeE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, nodeE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Remove(tokenD);
Assert.Equal(0, newList.Count);
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxNodeOrToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNodeOrToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNodeOrToken>)null));
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicResultProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
''' <summary>
''' Computes expansion of <see cref="DkmClrValue"/> instances.
''' </summary>
''' <remarks>
''' This class provides implementation for the Visual Basic ResultProvider component.
''' </remarks>
<DkmReportNonFatalWatsonException(ExcludeExceptionType:=GetType(NotImplementedException)), DkmContinueCorruptingException>
Friend NotInheritable Class VisualBasicResultProvider
Inherits ResultProvider
Public Sub New()
MyClass.New(New VisualBasicFormatter())
End Sub
Private Sub New(formatter As VisualBasicFormatter)
MyClass.New(formatter, formatter)
End Sub
Friend Sub New(formatter2 As IDkmClrFormatter2, fullNameProvider As IDkmClrFullNameProvider)
MyBase.New(formatter2, fullNameProvider)
End Sub
Friend Overrides ReadOnly Property StaticMembersString As String
Get
Return Resources.SharedMembers
End Get
End Property
Friend Overrides Function IsPrimitiveType(type As Type) As Boolean
Return type.IsPredefinedType()
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
''' <summary>
''' Computes expansion of <see cref="DkmClrValue"/> instances.
''' </summary>
''' <remarks>
''' This class provides implementation for the Visual Basic ResultProvider component.
''' </remarks>
<DkmReportNonFatalWatsonException(ExcludeExceptionType:=GetType(NotImplementedException)), DkmContinueCorruptingException>
Friend NotInheritable Class VisualBasicResultProvider
Inherits ResultProvider
Public Sub New()
MyClass.New(New VisualBasicFormatter())
End Sub
Private Sub New(formatter As VisualBasicFormatter)
MyClass.New(formatter, formatter)
End Sub
Friend Sub New(formatter2 As IDkmClrFormatter2, fullNameProvider As IDkmClrFullNameProvider)
MyBase.New(formatter2, fullNameProvider)
End Sub
Friend Overrides ReadOnly Property StaticMembersString As String
Get
Return Resources.SharedMembers
End Get
End Property
Friend Overrides Function IsPrimitiveType(type As Type) As Boolean
Return type.IsPredefinedType()
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharp/DocumentationComments/DocumentationCommentCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.DocumentationComments)]
[Order(After = PredefinedCommandHandlerNames.Rename)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal class DocumentationCommentCommandHandler
: AbstractDocumentationCommentCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentationCommentCommandHandler(
IUIThreadOperationExecutor uiThreadOperationExecutor,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(uiThreadOperationExecutor, undoHistoryRegistry, editorOperationsFactoryService)
{
}
protected override string ExteriorTriviaText => "///";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.DocumentationComments)]
[Order(After = PredefinedCommandHandlerNames.Rename)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal class DocumentationCommentCommandHandler
: AbstractDocumentationCommentCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentationCommentCommandHandler(
IUIThreadOperationExecutor uiThreadOperationExecutor,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(uiThreadOperationExecutor, undoHistoryRegistry, editorOperationsFactoryService)
{
}
protected override string ExteriorTriviaText => "///";
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Core/Implementation/CodeRefactorings/EditorLayerCodeActionHelpersService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeRefactorings
{
[ExportWorkspaceServiceFactory(typeof(ICodeRefactoringHelpersService), ServiceLayer.Editor), Shared]
internal class EditorLayerCodeActionHelpersService : IWorkspaceServiceFactory
{
private readonly IInlineRenameService _renameService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorLayerCodeActionHelpersService(IInlineRenameService renameService)
=> _renameService = renameService;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new CodeActionHelpersService(this);
private class CodeActionHelpersService : ICodeRefactoringHelpersService
{
private readonly EditorLayerCodeActionHelpersService _service;
public CodeActionHelpersService(EditorLayerCodeActionHelpersService service)
=> _service = service;
public bool ActiveInlineRenameSession
{
get
{
return _service._renameService.ActiveSession != 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.Composition;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeRefactorings
{
[ExportWorkspaceServiceFactory(typeof(ICodeRefactoringHelpersService), ServiceLayer.Editor), Shared]
internal class EditorLayerCodeActionHelpersService : IWorkspaceServiceFactory
{
private readonly IInlineRenameService _renameService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorLayerCodeActionHelpersService(IInlineRenameService renameService)
=> _renameService = renameService;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new CodeActionHelpersService(this);
private class CodeActionHelpersService : ICodeRefactoringHelpersService
{
private readonly EditorLayerCodeActionHelpersService _service;
public CodeActionHelpersService(EditorLayerCodeActionHelpersService service)
=> _service = service;
public bool ActiveInlineRenameSession
{
get
{
return _service._renameService.ActiveSession != null;
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class InternalKeywordRecommenderTests : 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 TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[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 TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task 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 TestAfterAbstract()
{
await VerifyKeywordAsync(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternal()
=> await VerifyAbsenceAsync(@"internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPublic()
=> await VerifyAbsenceAsync(@"public $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInternal()
=> await VerifyAbsenceAsync(@"static internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternalStatic()
=> await VerifyAbsenceAsync(@"internal static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInvalidInternal()
=> await VerifyAbsenceAsync(@"virtual internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPrivate()
=> await VerifyAbsenceAsync(@"private $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSealed()
{
await VerifyKeywordAsync(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInUsingDirective()
{
await VerifyAbsenceAsync(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInGlobalUsingDirective()
{
await VerifyAbsenceAsync(
@"global using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
=> await VerifyAbsenceAsync(@"class $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
=> await VerifyAbsenceAsync(@"delegate $$");
[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 TestAfterNestedVirtual()
{
await VerifyKeywordAsync(
@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[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 TestInProperty()
{
await VerifyKeywordAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAfterAccessor()
{
await VerifyKeywordAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAfterProtected()
{
await VerifyKeywordAsync(
@"class C {
int Goo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexer()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexerAfterAccessor()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { get { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInIndexerAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get { } internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexerAfterProtected()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { get { } protected $$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class InternalKeywordRecommenderTests : 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 TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[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 TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task 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 TestAfterAbstract()
{
await VerifyKeywordAsync(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternal()
=> await VerifyAbsenceAsync(@"internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPublic()
=> await VerifyAbsenceAsync(@"public $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInternal()
=> await VerifyAbsenceAsync(@"static internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternalStatic()
=> await VerifyAbsenceAsync(@"internal static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInvalidInternal()
=> await VerifyAbsenceAsync(@"virtual internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPrivate()
=> await VerifyAbsenceAsync(@"private $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSealed()
{
await VerifyKeywordAsync(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInUsingDirective()
{
await VerifyAbsenceAsync(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInGlobalUsingDirective()
{
await VerifyAbsenceAsync(
@"global using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
=> await VerifyAbsenceAsync(@"class $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
=> await VerifyAbsenceAsync(@"delegate $$");
[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 TestAfterNestedVirtual()
{
await VerifyKeywordAsync(
@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[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 TestInProperty()
{
await VerifyKeywordAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAfterAccessor()
{
await VerifyKeywordAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAfterProtected()
{
await VerifyKeywordAsync(
@"class C {
int Goo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexer()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexerAfterAccessor()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { get { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInIndexerAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get { } internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInIndexerAfterProtected()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { get { } protected $$");
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/CoreTest/BatchFixAllProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class BatchFixAllProviderTests
{
[Fact]
public async Task TestDefaultSelectionNestedFixers()
{
var testCode = @"
class TestClass {
int field = [|0|];
}
";
var fixedCode = $@"
class TestClass {{
int field = 1;
}}
";
// Three CodeFixProviders provide three actions
var codeFixes = ImmutableArray.Create(
ImmutableArray.Create(1),
ImmutableArray.Create(2),
ImmutableArray.Create(3));
await new CSharpTest(codeFixes, nested: true)
{
TestCode = testCode,
FixedCode = fixedCode,
}.RunAsync();
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
private class LiteralZeroAnalyzer : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("LiteralZero", "title", "message", "category", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(HandleNumericLiteralExpression, SyntaxKind.NumericLiteralExpression);
}
private void HandleNumericLiteralExpression(SyntaxNodeAnalysisContext context)
{
var node = (LiteralExpressionSyntax)context.Node;
if (node.Token.ValueText == "0")
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, node.Token.GetLocation()));
}
}
}
private class ReplaceZeroFix : CodeFixProvider
{
private readonly ImmutableArray<int> _replacements;
private readonly bool _nested;
public ReplaceZeroFix(ImmutableArray<int> replacements, bool nested)
{
Debug.Assert(replacements.All(replacement => replacement >= 0), $"Assertion failed: {nameof(replacements)}.All(replacement => replacement >= 0)");
_replacements = replacements;
_nested = nested;
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(LiteralZeroAnalyzer.Descriptor.Id);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
var fixes = new List<CodeAction>();
foreach (var replacement in _replacements)
{
fixes.Add(CodeAction.Create(
"ThisToBase",
cancellationToken => CreateChangedDocument(context.Document, diagnostic.Location.SourceSpan, replacement, cancellationToken),
$"{nameof(ReplaceZeroFix)}_{replacement}"));
}
if (_nested)
{
fixes = new List<CodeAction> { CodeAction.Create("Container", fixes.ToImmutableArray(), isInlinable: false) };
}
foreach (var fix in fixes)
{
context.RegisterCodeFix(fix, diagnostic);
}
}
return Task.CompletedTask;
}
private static async Task<Document> CreateChangedDocument(Document document, TextSpan sourceSpan, int replacement, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken);
var root = await tree.GetRootAsync(cancellationToken);
var token = root.FindToken(sourceSpan.Start);
var newToken = SyntaxFactory.Literal(token.LeadingTrivia, replacement.ToString(), replacement, token.TrailingTrivia);
return document.WithSyntaxRoot(root.ReplaceToken(token, newToken));
}
}
private class CSharpTest : CodeFixTest<DefaultVerifier>
{
private readonly ImmutableArray<ImmutableArray<int>> _replacementGroups;
private readonly bool _nested;
public CSharpTest(ImmutableArray<ImmutableArray<int>> replacementGroups, bool nested = false)
{
_replacementGroups = replacementGroups;
_nested = nested;
}
public override string Language => LanguageNames.CSharp;
public override Type SyntaxKindType => typeof(SyntaxKind);
protected override string DefaultFileExt => "cs";
protected override CompilationOptions CreateCompilationOptions()
{
return new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
}
protected override ParseOptions CreateParseOptions()
{
return new CSharpParseOptions(LanguageVersion.Default, DocumentationMode.Diagnose);
}
protected override IEnumerable<CodeFixProvider> GetCodeFixProviders()
{
foreach (var replacementGroup in _replacementGroups)
{
yield return new ReplaceZeroFix(replacementGroup, _nested);
}
}
protected override IEnumerable<DiagnosticAnalyzer> GetDiagnosticAnalyzers()
{
yield return new LiteralZeroAnalyzer();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class BatchFixAllProviderTests
{
[Fact]
public async Task TestDefaultSelectionNestedFixers()
{
var testCode = @"
class TestClass {
int field = [|0|];
}
";
var fixedCode = $@"
class TestClass {{
int field = 1;
}}
";
// Three CodeFixProviders provide three actions
var codeFixes = ImmutableArray.Create(
ImmutableArray.Create(1),
ImmutableArray.Create(2),
ImmutableArray.Create(3));
await new CSharpTest(codeFixes, nested: true)
{
TestCode = testCode,
FixedCode = fixedCode,
}.RunAsync();
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
private class LiteralZeroAnalyzer : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("LiteralZero", "title", "message", "category", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(HandleNumericLiteralExpression, SyntaxKind.NumericLiteralExpression);
}
private void HandleNumericLiteralExpression(SyntaxNodeAnalysisContext context)
{
var node = (LiteralExpressionSyntax)context.Node;
if (node.Token.ValueText == "0")
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, node.Token.GetLocation()));
}
}
}
private class ReplaceZeroFix : CodeFixProvider
{
private readonly ImmutableArray<int> _replacements;
private readonly bool _nested;
public ReplaceZeroFix(ImmutableArray<int> replacements, bool nested)
{
Debug.Assert(replacements.All(replacement => replacement >= 0), $"Assertion failed: {nameof(replacements)}.All(replacement => replacement >= 0)");
_replacements = replacements;
_nested = nested;
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(LiteralZeroAnalyzer.Descriptor.Id);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
var fixes = new List<CodeAction>();
foreach (var replacement in _replacements)
{
fixes.Add(CodeAction.Create(
"ThisToBase",
cancellationToken => CreateChangedDocument(context.Document, diagnostic.Location.SourceSpan, replacement, cancellationToken),
$"{nameof(ReplaceZeroFix)}_{replacement}"));
}
if (_nested)
{
fixes = new List<CodeAction> { CodeAction.Create("Container", fixes.ToImmutableArray(), isInlinable: false) };
}
foreach (var fix in fixes)
{
context.RegisterCodeFix(fix, diagnostic);
}
}
return Task.CompletedTask;
}
private static async Task<Document> CreateChangedDocument(Document document, TextSpan sourceSpan, int replacement, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken);
var root = await tree.GetRootAsync(cancellationToken);
var token = root.FindToken(sourceSpan.Start);
var newToken = SyntaxFactory.Literal(token.LeadingTrivia, replacement.ToString(), replacement, token.TrailingTrivia);
return document.WithSyntaxRoot(root.ReplaceToken(token, newToken));
}
}
private class CSharpTest : CodeFixTest<DefaultVerifier>
{
private readonly ImmutableArray<ImmutableArray<int>> _replacementGroups;
private readonly bool _nested;
public CSharpTest(ImmutableArray<ImmutableArray<int>> replacementGroups, bool nested = false)
{
_replacementGroups = replacementGroups;
_nested = nested;
}
public override string Language => LanguageNames.CSharp;
public override Type SyntaxKindType => typeof(SyntaxKind);
protected override string DefaultFileExt => "cs";
protected override CompilationOptions CreateCompilationOptions()
{
return new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
}
protected override ParseOptions CreateParseOptions()
{
return new CSharpParseOptions(LanguageVersion.Default, DocumentationMode.Diagnose);
}
protected override IEnumerable<CodeFixProvider> GetCodeFixProviders()
{
foreach (var replacementGroup in _replacementGroups)
{
yield return new ReplaceZeroFix(replacementGroup, _nested);
}
}
protected override IEnumerable<DiagnosticAnalyzer> GetDiagnosticAnalyzers()
{
yield return new LiteralZeroAnalyzer();
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/LockKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 LockKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public LockKeywordRecommender()
: base(SyntaxKind.LockKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class LockKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public LockKeywordRecommender()
: base(SyntaxKind.LockKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Scripting/Core/xlf/ScriptingResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../ScriptingResources.resx">
<body>
<trans-unit id="CannotSetLanguageSpecificOption">
<source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source>
<target state="translated">因為選項已經針對其他語言設定,所以無法設定 {0} 特定選項 {1}。</target>
<note />
</trans-unit>
<trans-unit id="StackOverflowWhileEvaluating">
<source>!<Stack overflow while evaluating object></source>
<target state="translated">!<評估物件時發生堆疊溢位></target>
<note />
</trans-unit>
<trans-unit id="CantAssignTo">
<source>Can't assign '{0}' to '{1}'.</source>
<target state="translated">無法將 '{0}' 指派給 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ExpectedAnAssemblyReference">
<source>Expected an assembly reference.</source>
<target state="translated">必須是組件參考。</target>
<note />
</trans-unit>
<trans-unit id="DisplayNameOrPathCannotBe">
<source>Display name or path cannot be empty.</source>
<target state="translated">顯示名稱或路徑不可為空白。</target>
<note />
</trans-unit>
<trans-unit id="AbsolutePathExpected">
<source>Absolute path expected</source>
<target state="translated">必須是絕對路徑</target>
<note />
</trans-unit>
<trans-unit id="GlobalsNotAssignable">
<source>The globals of type '{0}' is not assignable to '{1}'</source>
<target state="translated">類型 '{0}' 的全域變數不可指派給 '{1}'</target>
<note />
</trans-unit>
<trans-unit id="StartingStateIncompatible">
<source>Starting state was incompatible with script.</source>
<target state="translated">開始狀態與指令碼不相容。</target>
<note />
</trans-unit>
<trans-unit id="InvalidAssemblyName">
<source>Invalid assembly name</source>
<target state="translated">組件名稱無效</target>
<note />
</trans-unit>
<trans-unit id="InvalidCharactersInAssemblyName">
<source>Invalid characters in assemblyName</source>
<target state="translated">assemblyName 中的無效字元</target>
<note />
</trans-unit>
<trans-unit id="ScriptRequiresGlobalVariables">
<source>The script requires access to global variables but none were given</source>
<target state="translated">指令碼需要全域變數存取權,但未提供</target>
<note />
</trans-unit>
<trans-unit id="GlobalVariablesWithoutGlobalType">
<source>Global variables passed to a script without a global type</source>
<target state="translated">傳遞至沒有全域類型之指令碼的全域變數</target>
<note />
</trans-unit>
<trans-unit id="PlusAdditionalError">
<source>+ additional {0} error</source>
<target state="translated">+ 其他 {0} 錯誤</target>
<note />
</trans-unit>
<trans-unit id="PlusAdditionalErrors">
<source>+ additional {0} errors</source>
<target state="translated">+ 其他 {0} 錯誤</target>
<note />
</trans-unit>
<trans-unit id="AtFileLine">
<source> at {0} : {1}</source>
<target state="translated"> 在 {0} : {1}</target>
<note />
</trans-unit>
<trans-unit id="CannotSetReadOnlyVariable">
<source>Cannot set a read-only variable</source>
<target state="translated">無法設定唯讀變數</target>
<note />
</trans-unit>
<trans-unit id="CannotSetConstantVariable">
<source>Cannot set a constant variable</source>
<target state="translated">無法設定常數變數</target>
<note />
</trans-unit>
<trans-unit id="HelpPrompt">
<source>Type "#help" for more information.</source>
<target state="translated">如需詳細資訊,請輸入 "#help"。</target>
<note />
</trans-unit>
<trans-unit id="HelpText">
<source>Keyboard shortcuts:
Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.
Escape Clear the current submission.
UpArrow Replace the current submission with a previous submission.
DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards).
Ctrl-C Exit the REPL.
REPL commands:
#help Display help on available commands and key bindings.
Script directives:
#r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".
#load Load specified script file and execute it, e.g. #load "myScript.csx".</source>
<target state="translated">鍵盤快速鍵:
Enter 如果目前提交似乎已完成,會加以評估。否則會插入新行。
Escape 清除目前的提交。
UpArrow 以上一個提交取代目前的提交。
DownArrow 以下一個提交取代目前的提交 (前一個向後巡覽之後)。
Ctrl-C 結束 REPL。
REPL 命令:
#help 顯示可用命令與金鑰繫結的說明。
指令碼指示詞:
#r 將中繼資料參考加入指定的組件及其所有相依性中,例如 #r "myLib.dll"。
#load 載入指定的指令碼檔案並加以執行,例如 #load "myScript.csx"。</target>
<note />
</trans-unit>
<trans-unit id="AssemblyAlreadyLoaded">
<source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source>
<target state="translated">組件 '{0},版本 ={1}' 已從 '{2}' 載入。具有相同名稱和版本的不同組件不得載入: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="AssemblyAlreadyLoadedNotSigned">
<source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source>
<target state="translated">組件 '{0}' 已從 '{1}' 載入。具有相同名稱的不同組件除非已簽章,否則不得載入: '{2}'。</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../ScriptingResources.resx">
<body>
<trans-unit id="CannotSetLanguageSpecificOption">
<source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source>
<target state="translated">因為選項已經針對其他語言設定,所以無法設定 {0} 特定選項 {1}。</target>
<note />
</trans-unit>
<trans-unit id="StackOverflowWhileEvaluating">
<source>!<Stack overflow while evaluating object></source>
<target state="translated">!<評估物件時發生堆疊溢位></target>
<note />
</trans-unit>
<trans-unit id="CantAssignTo">
<source>Can't assign '{0}' to '{1}'.</source>
<target state="translated">無法將 '{0}' 指派給 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ExpectedAnAssemblyReference">
<source>Expected an assembly reference.</source>
<target state="translated">必須是組件參考。</target>
<note />
</trans-unit>
<trans-unit id="DisplayNameOrPathCannotBe">
<source>Display name or path cannot be empty.</source>
<target state="translated">顯示名稱或路徑不可為空白。</target>
<note />
</trans-unit>
<trans-unit id="AbsolutePathExpected">
<source>Absolute path expected</source>
<target state="translated">必須是絕對路徑</target>
<note />
</trans-unit>
<trans-unit id="GlobalsNotAssignable">
<source>The globals of type '{0}' is not assignable to '{1}'</source>
<target state="translated">類型 '{0}' 的全域變數不可指派給 '{1}'</target>
<note />
</trans-unit>
<trans-unit id="StartingStateIncompatible">
<source>Starting state was incompatible with script.</source>
<target state="translated">開始狀態與指令碼不相容。</target>
<note />
</trans-unit>
<trans-unit id="InvalidAssemblyName">
<source>Invalid assembly name</source>
<target state="translated">組件名稱無效</target>
<note />
</trans-unit>
<trans-unit id="InvalidCharactersInAssemblyName">
<source>Invalid characters in assemblyName</source>
<target state="translated">assemblyName 中的無效字元</target>
<note />
</trans-unit>
<trans-unit id="ScriptRequiresGlobalVariables">
<source>The script requires access to global variables but none were given</source>
<target state="translated">指令碼需要全域變數存取權,但未提供</target>
<note />
</trans-unit>
<trans-unit id="GlobalVariablesWithoutGlobalType">
<source>Global variables passed to a script without a global type</source>
<target state="translated">傳遞至沒有全域類型之指令碼的全域變數</target>
<note />
</trans-unit>
<trans-unit id="PlusAdditionalError">
<source>+ additional {0} error</source>
<target state="translated">+ 其他 {0} 錯誤</target>
<note />
</trans-unit>
<trans-unit id="PlusAdditionalErrors">
<source>+ additional {0} errors</source>
<target state="translated">+ 其他 {0} 錯誤</target>
<note />
</trans-unit>
<trans-unit id="AtFileLine">
<source> at {0} : {1}</source>
<target state="translated"> 在 {0} : {1}</target>
<note />
</trans-unit>
<trans-unit id="CannotSetReadOnlyVariable">
<source>Cannot set a read-only variable</source>
<target state="translated">無法設定唯讀變數</target>
<note />
</trans-unit>
<trans-unit id="CannotSetConstantVariable">
<source>Cannot set a constant variable</source>
<target state="translated">無法設定常數變數</target>
<note />
</trans-unit>
<trans-unit id="HelpPrompt">
<source>Type "#help" for more information.</source>
<target state="translated">如需詳細資訊,請輸入 "#help"。</target>
<note />
</trans-unit>
<trans-unit id="HelpText">
<source>Keyboard shortcuts:
Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.
Escape Clear the current submission.
UpArrow Replace the current submission with a previous submission.
DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards).
Ctrl-C Exit the REPL.
REPL commands:
#help Display help on available commands and key bindings.
Script directives:
#r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".
#load Load specified script file and execute it, e.g. #load "myScript.csx".</source>
<target state="translated">鍵盤快速鍵:
Enter 如果目前提交似乎已完成,會加以評估。否則會插入新行。
Escape 清除目前的提交。
UpArrow 以上一個提交取代目前的提交。
DownArrow 以下一個提交取代目前的提交 (前一個向後巡覽之後)。
Ctrl-C 結束 REPL。
REPL 命令:
#help 顯示可用命令與金鑰繫結的說明。
指令碼指示詞:
#r 將中繼資料參考加入指定的組件及其所有相依性中,例如 #r "myLib.dll"。
#load 載入指定的指令碼檔案並加以執行,例如 #load "myScript.csx"。</target>
<note />
</trans-unit>
<trans-unit id="AssemblyAlreadyLoaded">
<source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source>
<target state="translated">組件 '{0},版本 ={1}' 已從 '{2}' 載入。具有相同名稱和版本的不同組件不得載入: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="AssemblyAlreadyLoadedNotSigned">
<source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source>
<target state="translated">組件 '{0}' 已從 '{1}' 載入。具有相同名稱的不同組件除非已簽章,否則不得載入: '{2}'。</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.VisualStudio
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Imports Microsoft.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Partial Friend Class TempPECompiler
Implements IVbCompiler
Private ReadOnly _workspace As VisualStudioWorkspace
Private ReadOnly _projects As New List(Of TempPEProject)
Public Sub New(workspace As VisualStudioWorkspace)
Me._workspace = workspace
End Sub
Public Function Compile(ByVal pcWarnings As IntPtr, ByVal pcErrors As IntPtr, ByVal ppErrors As IntPtr) As Integer Implements IVbCompiler.Compile
' The CVbTempPECompiler never wants errors and simply passes in NULL.
Contract.ThrowIfFalse(ppErrors = IntPtr.Zero)
Dim metadataService = _workspace.Services.GetService(Of IMetadataService)
Dim errors As Integer = 0
For Each project In _projects
errors += project.CompileAndGetErrorCount(metadataService)
Next
If pcErrors <> IntPtr.Zero Then
Marshal.WriteInt32(pcErrors, errors)
End If
Return VSConstants.S_OK
End Function
Public Function CreateProject(wszName As String,
punkProject As Object,
pProjHier As IVsHierarchy,
pVbCompilerHost As IVbCompilerHost) As IVbCompilerProject Implements IVbCompiler.CreateProject
Dim project = New TempPEProject(pVbCompilerHost)
_projects.Add(project)
Return project
End Function
Public Function IsValidIdentifier(wszIdentifier As String) As Boolean Implements IVbCompiler.IsValidIdentifier
Throw New NotImplementedException()
End Function
Public Sub RegisterVbCompilerHost(pVbCompilerHost As IVbCompilerHost) Implements IVbCompiler.RegisterVbCompilerHost
' The project system registers IVbCompilerHosts with us by calling this method, but
' don't care about it in the first place. Thus this is a no-op.
End Sub
Public Sub SetDebugSwitches(dbgSwitches() As Boolean) Implements IVbCompiler.SetDebugSwitches
Throw New NotImplementedException()
End Sub
Public Sub SetLoggingOptions(options As UInteger) Implements IVbCompiler.SetLoggingOptions
Throw New NotImplementedException()
End Sub
Public Sub SetOutputLevel(OutputLevel As OutputLevel) Implements IVbCompiler.SetOutputLevel
Throw New NotImplementedException()
End Sub
Public Sub SetWatsonType(WatsonType As WatsonType, WatsonLcid As Integer, wszAdditionalFiles As String) Implements IVbCompiler.SetWatsonType
Throw New NotImplementedException()
End Sub
Public Sub StartBackgroundCompiler() Implements IVbCompiler.StartBackgroundCompiler
Throw New NotImplementedException()
End Sub
Public Sub StopBackgroundCompiler() Implements IVbCompiler.StopBackgroundCompiler
Throw New NotImplementedException()
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.VisualStudio
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Imports Microsoft.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Partial Friend Class TempPECompiler
Implements IVbCompiler
Private ReadOnly _workspace As VisualStudioWorkspace
Private ReadOnly _projects As New List(Of TempPEProject)
Public Sub New(workspace As VisualStudioWorkspace)
Me._workspace = workspace
End Sub
Public Function Compile(ByVal pcWarnings As IntPtr, ByVal pcErrors As IntPtr, ByVal ppErrors As IntPtr) As Integer Implements IVbCompiler.Compile
' The CVbTempPECompiler never wants errors and simply passes in NULL.
Contract.ThrowIfFalse(ppErrors = IntPtr.Zero)
Dim metadataService = _workspace.Services.GetService(Of IMetadataService)
Dim errors As Integer = 0
For Each project In _projects
errors += project.CompileAndGetErrorCount(metadataService)
Next
If pcErrors <> IntPtr.Zero Then
Marshal.WriteInt32(pcErrors, errors)
End If
Return VSConstants.S_OK
End Function
Public Function CreateProject(wszName As String,
punkProject As Object,
pProjHier As IVsHierarchy,
pVbCompilerHost As IVbCompilerHost) As IVbCompilerProject Implements IVbCompiler.CreateProject
Dim project = New TempPEProject(pVbCompilerHost)
_projects.Add(project)
Return project
End Function
Public Function IsValidIdentifier(wszIdentifier As String) As Boolean Implements IVbCompiler.IsValidIdentifier
Throw New NotImplementedException()
End Function
Public Sub RegisterVbCompilerHost(pVbCompilerHost As IVbCompilerHost) Implements IVbCompiler.RegisterVbCompilerHost
' The project system registers IVbCompilerHosts with us by calling this method, but
' don't care about it in the first place. Thus this is a no-op.
End Sub
Public Sub SetDebugSwitches(dbgSwitches() As Boolean) Implements IVbCompiler.SetDebugSwitches
Throw New NotImplementedException()
End Sub
Public Sub SetLoggingOptions(options As UInteger) Implements IVbCompiler.SetLoggingOptions
Throw New NotImplementedException()
End Sub
Public Sub SetOutputLevel(OutputLevel As OutputLevel) Implements IVbCompiler.SetOutputLevel
Throw New NotImplementedException()
End Sub
Public Sub SetWatsonType(WatsonType As WatsonType, WatsonLcid As Integer, wszAdditionalFiles As String) Implements IVbCompiler.SetWatsonType
Throw New NotImplementedException()
End Sub
Public Sub StartBackgroundCompiler() Implements IVbCompiler.StartBackgroundCompiler
Throw New NotImplementedException()
End Sub
Public Sub StopBackgroundCompiler() Implements IVbCompiler.StopBackgroundCompiler
Throw New NotImplementedException()
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/Binder/ContextualAttributeBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Each application of an attribute is effectively a constructor call. Since the attribute constructor
/// might have a CallerMemberName parameter, we need to keep track of which method/property/event
/// the attribute is on/in (e.g. on a parameter) so that we can use the name of that member as the
/// CallerMemberName argument.
/// </summary>
internal sealed class ContextualAttributeBinder : Binder
{
private readonly Symbol _attributeTarget;
private readonly Symbol _attributedMember;
/// <param name="enclosing">Next binder in the chain (enclosing).</param>
/// <param name="symbol">Symbol to which the attribute was applied (e.g. a parameter).</param>
public ContextualAttributeBinder(Binder enclosing, Symbol symbol)
: base(enclosing, enclosing.Flags | BinderFlags.InContextualAttributeBinder)
{
_attributeTarget = symbol;
_attributedMember = GetAttributedMember(symbol);
}
/// <summary>
/// We're binding an attribute and this is the member to/in which the attribute was applied.
/// </summary>
/// <remarks>
/// Method, property, event, or null.
/// A virtual property on Binder (i.e. our usual pattern) would be more robust, but the applicability
/// of this property is so narrow that it doesn't seem worthwhile.
/// </remarks>
internal Symbol AttributedMember
{
get
{
return _attributedMember;
}
}
/// <summary>
/// Walk up to the nearest method/property/event.
/// </summary>
private static Symbol GetAttributedMember(Symbol symbol)
{
for (; (object)symbol != null; symbol = symbol.ContainingSymbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
return symbol;
}
}
return symbol;
}
internal Symbol AttributeTarget
{
get
{
return _attributeTarget;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Each application of an attribute is effectively a constructor call. Since the attribute constructor
/// might have a CallerMemberName parameter, we need to keep track of which method/property/event
/// the attribute is on/in (e.g. on a parameter) so that we can use the name of that member as the
/// CallerMemberName argument.
/// </summary>
internal sealed class ContextualAttributeBinder : Binder
{
private readonly Symbol _attributeTarget;
private readonly Symbol _attributedMember;
/// <param name="enclosing">Next binder in the chain (enclosing).</param>
/// <param name="symbol">Symbol to which the attribute was applied (e.g. a parameter).</param>
public ContextualAttributeBinder(Binder enclosing, Symbol symbol)
: base(enclosing, enclosing.Flags | BinderFlags.InContextualAttributeBinder)
{
_attributeTarget = symbol;
_attributedMember = GetAttributedMember(symbol);
}
/// <summary>
/// We're binding an attribute and this is the member to/in which the attribute was applied.
/// </summary>
/// <remarks>
/// Method, property, event, or null.
/// A virtual property on Binder (i.e. our usual pattern) would be more robust, but the applicability
/// of this property is so narrow that it doesn't seem worthwhile.
/// </remarks>
internal Symbol AttributedMember
{
get
{
return _attributedMember;
}
}
/// <summary>
/// Walk up to the nearest method/property/event.
/// </summary>
private static Symbol GetAttributedMember(Symbol symbol)
{
for (; (object)symbol != null; symbol = symbol.ContainingSymbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
return symbol;
}
}
return symbol;
}
internal Symbol AttributeTarget
{
get
{
return _attributeTarget;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.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.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.Name = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.[|$${|Definition:Name|}|] = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.{|Definition:[|$$Name|]|} = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542705")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class Program1
Shared str As String = "abc"
Shared Sub Main(args As String())
Dim employee08 = New With {.[|$${|Definition:Category|}|] = Category(str), Key.Name = 2 + 1}
Dim employee01 = New With {Key.Category = 2 + 1, Key.Name = "Bob"}
End Sub
Shared Function Category(str As String)
Category = str
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(3284, "https://github.com/dotnet/roslyn/issues/3284")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCaseInsensitiveAnonymousType1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = New With {.[|$${|Definition:A|}|] = 1}
Dim y = New With {.[|A|] = 2}
Dim z = New With {.[|a|] = 3}
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(3284, "https://github.com/dotnet/roslyn/issues/3284")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCaseInsensitiveAnonymousType2(kind As TestKind, host As TestHost) As System.Threading.Tasks.Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = New With {.[|A|] = 1}
Dim y = New With {.[|A|] = 2}
Dim z = New With {.[|$${|Definition:a|}|] = 3}
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.Name = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.[|$${|Definition:Name|}|] = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542553")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.{|Definition:[|$$Name|]|} = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542705")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousType5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class Program1
Shared str As String = "abc"
Shared Sub Main(args As String())
Dim employee08 = New With {.[|$${|Definition:Category|}|] = Category(str), Key.Name = 2 + 1}
Dim employee01 = New With {Key.Category = 2 + 1, Key.Name = "Bob"}
End Sub
Shared Function Category(str As String)
Category = str
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(3284, "https://github.com/dotnet/roslyn/issues/3284")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCaseInsensitiveAnonymousType1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = New With {.[|$${|Definition:A|}|] = 1}
Dim y = New With {.[|A|] = 2}
Dim z = New With {.[|a|] = 3}
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(3284, "https://github.com/dotnet/roslyn/issues/3284")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCaseInsensitiveAnonymousType2(kind As TestKind, host As TestHost) As System.Threading.Tasks.Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = New With {.[|A|] = 1}
Dim y = New With {.[|A|] = 2}
Dim z = New With {.[|$${|Definition:a|}|] = 3}
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/IPerformanceTrackerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
internal interface IPerformanceTrackerService : IWorkspaceService
{
void AddSnapshot(IEnumerable<AnalyzerPerformanceInfo> snapshot, int unitCount);
void GenerateReport(List<ExpensiveAnalyzerInfo> badAnalyzers);
event EventHandler SnapshotAdded;
}
internal struct ExpensiveAnalyzerInfo
{
public readonly bool BuiltIn;
public readonly string AnalyzerId;
public readonly string AnalyzerIdHash;
public readonly double LocalOutlierFactor;
public readonly double Average;
public readonly double AdjustedStandardDeviation;
public ExpensiveAnalyzerInfo(bool builtIn, string analyzerId, double lof_value, double average, double stddev) : this()
{
BuiltIn = builtIn;
AnalyzerId = analyzerId;
AnalyzerIdHash = analyzerId.GetHashCode().ToString();
LocalOutlierFactor = lof_value;
Average = average;
AdjustedStandardDeviation = stddev;
}
public string PIISafeAnalyzerId => BuiltIn ? AnalyzerId : AnalyzerIdHash;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
internal interface IPerformanceTrackerService : IWorkspaceService
{
void AddSnapshot(IEnumerable<AnalyzerPerformanceInfo> snapshot, int unitCount);
void GenerateReport(List<ExpensiveAnalyzerInfo> badAnalyzers);
event EventHandler SnapshotAdded;
}
internal struct ExpensiveAnalyzerInfo
{
public readonly bool BuiltIn;
public readonly string AnalyzerId;
public readonly string AnalyzerIdHash;
public readonly double LocalOutlierFactor;
public readonly double Average;
public readonly double AdjustedStandardDeviation;
public ExpensiveAnalyzerInfo(bool builtIn, string analyzerId, double lof_value, double average, double stddev) : this()
{
BuiltIn = builtIn;
AnalyzerId = analyzerId;
AnalyzerIdHash = analyzerId.GetHashCode().ToString();
LocalOutlierFactor = lof_value;
Average = average;
AdjustedStandardDeviation = stddev;
}
public string PIISafeAnalyzerId => BuiltIn ? AnalyzerId : AnalyzerIdHash;
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/Symbols/LexicalSortKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A structure used to lexically order symbols. For performance, it's important that this be
/// a STRUCTURE, and be able to be returned from a symbol without doing any additional allocations (even
/// if nothing is cached yet).
/// </summary>
internal struct LexicalSortKey
{
private int _treeOrdinal;
private int _position;
// If -1, symbols is in metadata or otherwise not in source
public int TreeOrdinal
{
get { return _treeOrdinal; }
}
// Offset of location within the tree. Doesn't need to exactly that span returns by Locations, just
// be good enough to sort. In order word, we don't need to go to extra work to return the location of the identifier,
// just some syntax location is fine.
//
// Negative value indicates that the structure was not initialized yet, is used for lazy
// initializations only along with LexicalSortKey.NotInitialized
public int Position
{
get { return _position; }
}
public static readonly LexicalSortKey NotInSource = new LexicalSortKey() { _treeOrdinal = -1, _position = 0 };
public static readonly LexicalSortKey NotInitialized = new LexicalSortKey() { _treeOrdinal = -1, _position = -1 };
// Put other synthesized members right before synthesized constructors.
public static LexicalSortKey GetSynthesizedMemberKey(int offset) => new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 2 - offset };
// Dev12 compiler adds synthetic constructors to the child list after adding all other members.
// Methods are emitted in the children order, but synthetic cctors would be deferred
// until later when it is known if they can be optimized or not.
// As a result the last emitted method tokens are synthetic ctor and then synthetic cctor (if not optimized)
// Since it is not too hard, we will try keeping the same order just to be easy on metadata diffing tools and such.
public static readonly LexicalSortKey SynthesizedCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 1 };
public static readonly LexicalSortKey SynthesizedCCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue };
private LexicalSortKey(int treeOrdinal, int position)
{
Debug.Assert(position >= 0);
Debug.Assert(treeOrdinal >= 0);
_treeOrdinal = treeOrdinal;
_position = position;
}
private LexicalSortKey(SyntaxTree tree, int position, CSharpCompilation compilation)
: this(tree == null ? -1 : compilation.GetSyntaxTreeOrdinal(tree), position)
{
}
public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation)
: this(syntaxRef.SyntaxTree, syntaxRef.Span.Start, compilation)
{
}
// WARNING: Only use this if the location is obtainable without allocating it (even if cached later). E.g., only
// if the location object is stored in the constructor of the symbol.
public LexicalSortKey(Location location, CSharpCompilation compilation)
: this((SyntaxTree)location.SourceTree, location.SourceSpan.Start, compilation)
{
}
// WARNING: Only use this if the node is obtainable without allocating it (even if cached later). E.g., only
// if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax()
// call on a SyntaxReference.
public LexicalSortKey(CSharpSyntaxNode node, CSharpCompilation compilation)
: this(node.SyntaxTree, node.SpanStart, compilation)
{
}
// WARNING: Only use this if the token is obtainable without allocating it (even if cached later). E.g., only
// if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax()
// call on a SyntaxReference.
public LexicalSortKey(SyntaxToken token, CSharpCompilation compilation)
: this((SyntaxTree)token.SyntaxTree, token.SpanStart, compilation)
{
}
/// <summary>
/// Compare two lexical sort keys in a compilation.
/// </summary>
public static int Compare(LexicalSortKey xSortKey, LexicalSortKey ySortKey)
{
int comparison;
if (xSortKey.TreeOrdinal != ySortKey.TreeOrdinal)
{
if (xSortKey.TreeOrdinal < 0)
{
return 1;
}
else if (ySortKey.TreeOrdinal < 0)
{
return -1;
}
comparison = xSortKey.TreeOrdinal - ySortKey.TreeOrdinal;
Debug.Assert(comparison != 0);
return comparison;
}
return xSortKey.Position - ySortKey.Position;
}
public static LexicalSortKey First(LexicalSortKey xSortKey, LexicalSortKey ySortKey)
{
int comparison = Compare(xSortKey, ySortKey);
return comparison > 0 ? ySortKey : xSortKey;
}
public bool IsInitialized
{
get
{
return Volatile.Read(ref _position) >= 0;
}
}
public void SetFrom(LexicalSortKey other)
{
Debug.Assert(other.IsInitialized);
_treeOrdinal = other._treeOrdinal;
Volatile.Write(ref _position, other._position);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A structure used to lexically order symbols. For performance, it's important that this be
/// a STRUCTURE, and be able to be returned from a symbol without doing any additional allocations (even
/// if nothing is cached yet).
/// </summary>
internal struct LexicalSortKey
{
private int _treeOrdinal;
private int _position;
// If -1, symbols is in metadata or otherwise not in source
public int TreeOrdinal
{
get { return _treeOrdinal; }
}
// Offset of location within the tree. Doesn't need to exactly that span returns by Locations, just
// be good enough to sort. In order word, we don't need to go to extra work to return the location of the identifier,
// just some syntax location is fine.
//
// Negative value indicates that the structure was not initialized yet, is used for lazy
// initializations only along with LexicalSortKey.NotInitialized
public int Position
{
get { return _position; }
}
public static readonly LexicalSortKey NotInSource = new LexicalSortKey() { _treeOrdinal = -1, _position = 0 };
public static readonly LexicalSortKey NotInitialized = new LexicalSortKey() { _treeOrdinal = -1, _position = -1 };
// Put other synthesized members right before synthesized constructors.
public static LexicalSortKey GetSynthesizedMemberKey(int offset) => new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 2 - offset };
// Dev12 compiler adds synthetic constructors to the child list after adding all other members.
// Methods are emitted in the children order, but synthetic cctors would be deferred
// until later when it is known if they can be optimized or not.
// As a result the last emitted method tokens are synthetic ctor and then synthetic cctor (if not optimized)
// Since it is not too hard, we will try keeping the same order just to be easy on metadata diffing tools and such.
public static readonly LexicalSortKey SynthesizedCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 1 };
public static readonly LexicalSortKey SynthesizedCCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue };
private LexicalSortKey(int treeOrdinal, int position)
{
Debug.Assert(position >= 0);
Debug.Assert(treeOrdinal >= 0);
_treeOrdinal = treeOrdinal;
_position = position;
}
private LexicalSortKey(SyntaxTree tree, int position, CSharpCompilation compilation)
: this(tree == null ? -1 : compilation.GetSyntaxTreeOrdinal(tree), position)
{
}
public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation)
: this(syntaxRef.SyntaxTree, syntaxRef.Span.Start, compilation)
{
}
// WARNING: Only use this if the location is obtainable without allocating it (even if cached later). E.g., only
// if the location object is stored in the constructor of the symbol.
public LexicalSortKey(Location location, CSharpCompilation compilation)
: this((SyntaxTree)location.SourceTree, location.SourceSpan.Start, compilation)
{
}
// WARNING: Only use this if the node is obtainable without allocating it (even if cached later). E.g., only
// if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax()
// call on a SyntaxReference.
public LexicalSortKey(CSharpSyntaxNode node, CSharpCompilation compilation)
: this(node.SyntaxTree, node.SpanStart, compilation)
{
}
// WARNING: Only use this if the token is obtainable without allocating it (even if cached later). E.g., only
// if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax()
// call on a SyntaxReference.
public LexicalSortKey(SyntaxToken token, CSharpCompilation compilation)
: this((SyntaxTree)token.SyntaxTree, token.SpanStart, compilation)
{
}
/// <summary>
/// Compare two lexical sort keys in a compilation.
/// </summary>
public static int Compare(LexicalSortKey xSortKey, LexicalSortKey ySortKey)
{
int comparison;
if (xSortKey.TreeOrdinal != ySortKey.TreeOrdinal)
{
if (xSortKey.TreeOrdinal < 0)
{
return 1;
}
else if (ySortKey.TreeOrdinal < 0)
{
return -1;
}
comparison = xSortKey.TreeOrdinal - ySortKey.TreeOrdinal;
Debug.Assert(comparison != 0);
return comparison;
}
return xSortKey.Position - ySortKey.Position;
}
public static LexicalSortKey First(LexicalSortKey xSortKey, LexicalSortKey ySortKey)
{
int comparison = Compare(xSortKey, ySortKey);
return comparison > 0 ? ySortKey : xSortKey;
}
public bool IsInitialized
{
get
{
return Volatile.Read(ref _position) >= 0;
}
}
public void SetFrom(LexicalSortKey other)
{
Debug.Assert(other.IsInitialized);
_treeOrdinal = other._treeOrdinal;
Volatile.Write(ref _position, other._position);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ShortKeywordRecommenderTests : 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 TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"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(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 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(short 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 ShortKeywordRecommenderTests : 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 TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"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(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 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(short 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 | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/Core/Test/DebuggerIntelliSense/VisualBasicDebuggerIntellisenseTests.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.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
<[UseExportProvider]>
Public Class VisualBasicDebuggerIntellisenseTests
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function QueryVariables() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar = From x In "asdf"
Where [|x = "d"|]
Select x
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function EnteringMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
[|Sub Main(args As String())|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("args")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ExitingMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = 4
[|End Sub|]
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("args")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SingleLineLambda() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = [|Function(x) x + 5|]
z(3)
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function MultiLineLambda() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = [|Function(x)|]
Return x + 5
End Function
z(3)
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalVariables() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("bar")
Await state.VerifyCompletionAndDotAfter("y")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionAfterReturn() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, True)
Await state.VerifyCompletionAndDotAfter("bar")
Await state.VerifyCompletionAndDotAfter("y")
Await state.VerifyCompletionAndDotAfter("z")
state.SendReturn()
Await state.VerifyCompletionAndDotAfter("y")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TypeALineTenTimes() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, True)
For xx = 0 To 10
state.SendTypeChars("z")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("z")
state.SendTab()
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
state.SendReturn()
Await state.AssertNoCompletionSession()
state.SendReturn()
Assert.DoesNotContain("z", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Next
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInParameterizedConstructor() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new String(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInMethodCall() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Main(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInGenericMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Self(Of Integer)(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionInExpression() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new List(Of String) From { a")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionShowTypesFromProjectReference() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>ReferencedProject</ProjectReference>
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="ReferencedProject">
<Document>
Public Class AClass
Sub New()
End Sub
End Class
</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new AClass")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("AClass")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionForGenericType() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Self(Of ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalsInForBlock() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
Dim y = 3
Dim z = 4
For xx As Integer = 1 To 10
[|Dim q = xx + 2|]
Next
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("q")
Await state.VerifyCompletionAndDotAfter("xx")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function StoppedOnEndSub() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(o as Integer)
[|End Sub|]
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("o")
End Using
End Function
<WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function StoppedOnEndProperty() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Class C
Public Property x As Integer
Get
Return 0
End Get
Set(value As Integer)
[|End Set|]
End Property
End Class</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("value")
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
<[UseExportProvider]>
Public Class VisualBasicDebuggerIntellisenseTests
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function QueryVariables() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar = From x In "asdf"
Where [|x = "d"|]
Select x
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function EnteringMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
[|Sub Main(args As String())|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("args")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ExitingMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = 4
[|End Sub|]
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("args")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SingleLineLambda() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = [|Function(x) x + 5|]
z(3)
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function MultiLineLambda() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim z = [|Function(x)|]
Return x + 5
End Function
z(3)
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("x")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalVariables() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("bar")
Await state.VerifyCompletionAndDotAfter("y")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionAfterReturn() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim bar as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, True)
Await state.VerifyCompletionAndDotAfter("bar")
Await state.VerifyCompletionAndDotAfter("y")
Await state.VerifyCompletionAndDotAfter("z")
state.SendReturn()
Await state.VerifyCompletionAndDotAfter("y")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TypeALineTenTimes() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, True)
For xx = 0 To 10
state.SendTypeChars("z")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("z")
state.SendTab()
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
state.SendReturn()
Await state.AssertNoCompletionSession()
state.SendReturn()
Assert.DoesNotContain("z", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Next
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInParameterizedConstructor() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new String(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInMethodCall() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Main(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInGenericMethod() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Self(Of Integer)(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionInExpression() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new List(Of String) From { a")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionShowTypesFromProjectReference() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>ReferencedProject</ProjectReference>
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="ReferencedProject">
<Document>
Public Class AClass
Sub New()
End Sub
End Class
</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("new AClass")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("AClass")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionForGenericType() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Self(Of T)(goo as T)
Return goo
End Sub
Sub Main(args As String())
Dim xx as String = "boo"
[|Dim y = 3|]
Dim z = 4
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
state.SendTypeChars("Self(Of ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalsInForBlock() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(args As String())
Dim xx as String = "boo"
Dim y = 3
Dim z = 4
For xx As Integer = 1 To 10
[|Dim q = xx + 2|]
Next
End Sub
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("q")
Await state.VerifyCompletionAndDotAfter("xx")
Await state.VerifyCompletionAndDotAfter("z")
End Using
End Function
<WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function StoppedOnEndSub() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
Sub Main(o as Integer)
[|End Sub|]
End Module</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("o")
End Using
End Function
<WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function StoppedOnEndProperty() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Class C
Public Property x As Integer
Get
Return 0
End Get
Set(value As Integer)
[|End Set|]
End Property
End Class</Document>
</Project>
</Workspace>
Using state = TestState.CreateVisualBasicTestState(text, False)
Await state.VerifyCompletionAndDotAfter("value")
End Using
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Symbols/MissingAssemblySymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="MissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
''' an assembly that couldn't be found.
''' </summary>
Friend Class MissingAssemblySymbol
Inherits AssemblySymbol
Protected ReadOnly m_Identity As AssemblyIdentity
Protected ReadOnly m_ModuleSymbol As MissingModuleSymbol
Private _lazyModules As ImmutableArray(Of ModuleSymbol)
Public Sub New(identity As AssemblyIdentity)
Debug.Assert(identity IsNot Nothing)
m_Identity = identity
m_ModuleSymbol = New MissingModuleSymbol(Me, 0)
End Sub
Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property IsLinked As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetDeclaredSpecialTypeMember(member As SpecialMember) As Symbol
Return Nothing
End Function
Public Overrides ReadOnly Property Identity As AssemblyIdentity
Get
Return m_Identity
End Get
End Property
Public Overrides ReadOnly Property AssemblyVersionPattern As Version
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Get
Return Identity.PublicKey
End Get
End Property
Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
Get
If _lazyModules.IsDefault Then
_lazyModules = ImmutableArray.Create(Of ModuleSymbol)(m_ModuleSymbol)
End If
Return _lazyModules
End Get
End Property
Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
Return m_ModuleSymbol.GlobalNamespace
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return m_Identity.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return Equals(TryCast(obj, MissingAssemblySymbol))
End Function
Public Overloads Function Equals(other As MissingAssemblySymbol) As Boolean
Return other IsNot Nothing AndAlso (Me Is other OrElse m_Identity.Equals(other.m_Identity))
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
Return ImmutableArray(Of AssemblySymbol).Empty
End Function
Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Return ImmutableArray(Of AssemblySymbol).Empty
End Function
Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
Return SpecializedCollections.EmptyEnumerable(Of ImmutableArray(Of Byte))()
End Function
Public Overrides ReadOnly Property TypeNames As ICollection(Of String)
Get
Return SpecializedCollections.EmptyCollection(Of String)()
End Get
End Property
Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String)
Get
Return SpecializedCollections.EmptyCollection(Of String)()
End Get
End Property
Friend Overrides Function AreInternalsVisibleToThisAssembly(other As AssemblySymbol) As Boolean
Return False
End Function
Friend Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol
Dim result = m_ModuleSymbol.LookupTopLevelMetadataType(emittedName)
Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol)
Return result
End Function
Friend NotOverridable Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol)
Return SpecializedCollections.EmptyEnumerable(Of NamedTypeSymbol)()
End Function
Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetMetadata() As AssemblyMetadata
Return Nothing
End Function
End Class
''' <summary>
''' AssemblySymbol to represent missing, for whatever reason, CorLibrary.
''' The symbol is created by ReferenceManager on as needed basis and is shared by all compilations
''' with missing CorLibraries.
''' </summary>
Friend NotInheritable Class MissingCorLibrarySymbol
Inherits MissingAssemblySymbol
Friend Shared ReadOnly Instance As MissingCorLibrarySymbol = New MissingCorLibrarySymbol()
''' <summary>
''' An array of cached Cor types defined in this assembly.
''' Lazily filled by GetDeclaredSpecialType method.
''' </summary>
Private _lazySpecialTypes() As NamedTypeSymbol
Private Sub New()
MyBase.New(New AssemblyIdentity("<Missing Core Assembly>"))
Me.SetCorLibrary(Me)
End Sub
''' <summary>
''' Lookup declaration for predefined CorLib type in this Assembly. Only should be
''' called if it is know that this is the Cor Library (mscorlib).
''' </summary>
''' <param name="type"></param>
Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol
#If DEBUG Then
For Each [module] In Me.Modules
Debug.Assert([module].GetReferencedAssemblies().Length = 0)
Next
#End If
If _lazySpecialTypes Is Nothing Then
Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing)
End If
If _lazySpecialTypes(type) Is Nothing Then
Dim emittedFullName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True)
Dim corType As NamedTypeSymbol = New MissingMetadataTypeSymbol.TopLevel(m_ModuleSymbol, emittedFullName, type)
Interlocked.CompareExchange(_lazySpecialTypes(type), corType, Nothing)
End If
Return _lazySpecialTypes(type)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="MissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
''' an assembly that couldn't be found.
''' </summary>
Friend Class MissingAssemblySymbol
Inherits AssemblySymbol
Protected ReadOnly m_Identity As AssemblyIdentity
Protected ReadOnly m_ModuleSymbol As MissingModuleSymbol
Private _lazyModules As ImmutableArray(Of ModuleSymbol)
Public Sub New(identity As AssemblyIdentity)
Debug.Assert(identity IsNot Nothing)
m_Identity = identity
m_ModuleSymbol = New MissingModuleSymbol(Me, 0)
End Sub
Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property IsLinked As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetDeclaredSpecialTypeMember(member As SpecialMember) As Symbol
Return Nothing
End Function
Public Overrides ReadOnly Property Identity As AssemblyIdentity
Get
Return m_Identity
End Get
End Property
Public Overrides ReadOnly Property AssemblyVersionPattern As Version
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Get
Return Identity.PublicKey
End Get
End Property
Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
Get
If _lazyModules.IsDefault Then
_lazyModules = ImmutableArray.Create(Of ModuleSymbol)(m_ModuleSymbol)
End If
Return _lazyModules
End Get
End Property
Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
Return m_ModuleSymbol.GlobalNamespace
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return m_Identity.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return Equals(TryCast(obj, MissingAssemblySymbol))
End Function
Public Overloads Function Equals(other As MissingAssemblySymbol) As Boolean
Return other IsNot Nothing AndAlso (Me Is other OrElse m_Identity.Equals(other.m_Identity))
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
Return ImmutableArray(Of AssemblySymbol).Empty
End Function
Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Return ImmutableArray(Of AssemblySymbol).Empty
End Function
Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
Return SpecializedCollections.EmptyEnumerable(Of ImmutableArray(Of Byte))()
End Function
Public Overrides ReadOnly Property TypeNames As ICollection(Of String)
Get
Return SpecializedCollections.EmptyCollection(Of String)()
End Get
End Property
Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String)
Get
Return SpecializedCollections.EmptyCollection(Of String)()
End Get
End Property
Friend Overrides Function AreInternalsVisibleToThisAssembly(other As AssemblySymbol) As Boolean
Return False
End Function
Friend Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol
Dim result = m_ModuleSymbol.LookupTopLevelMetadataType(emittedName)
Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol)
Return result
End Function
Friend NotOverridable Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol)
Return SpecializedCollections.EmptyEnumerable(Of NamedTypeSymbol)()
End Function
Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetMetadata() As AssemblyMetadata
Return Nothing
End Function
End Class
''' <summary>
''' AssemblySymbol to represent missing, for whatever reason, CorLibrary.
''' The symbol is created by ReferenceManager on as needed basis and is shared by all compilations
''' with missing CorLibraries.
''' </summary>
Friend NotInheritable Class MissingCorLibrarySymbol
Inherits MissingAssemblySymbol
Friend Shared ReadOnly Instance As MissingCorLibrarySymbol = New MissingCorLibrarySymbol()
''' <summary>
''' An array of cached Cor types defined in this assembly.
''' Lazily filled by GetDeclaredSpecialType method.
''' </summary>
Private _lazySpecialTypes() As NamedTypeSymbol
Private Sub New()
MyBase.New(New AssemblyIdentity("<Missing Core Assembly>"))
Me.SetCorLibrary(Me)
End Sub
''' <summary>
''' Lookup declaration for predefined CorLib type in this Assembly. Only should be
''' called if it is know that this is the Cor Library (mscorlib).
''' </summary>
''' <param name="type"></param>
Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol
#If DEBUG Then
For Each [module] In Me.Modules
Debug.Assert([module].GetReferencedAssemblies().Length = 0)
Next
#End If
If _lazySpecialTypes Is Nothing Then
Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing)
End If
If _lazySpecialTypes(type) Is Nothing Then
Dim emittedFullName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True)
Dim corType As NamedTypeSymbol = New MissingMetadataTypeSymbol.TopLevel(m_ModuleSymbol, emittedFullName, type)
Interlocked.CompareExchange(_lazySpecialTypes(type), corType, Nothing)
End If
Return _lazySpecialTypes(type)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/Core/Portable/Shared/Naming/FallbackNamingRules.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.NamingStyles;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Naming
{
internal static class FallbackNamingRules
{
/// <summary>
/// Standard symbol names if the user doesn't have any existing naming rules.
/// </summary>
public static readonly ImmutableArray<NamingRule> Default = ImmutableArray.Create(
// Symbols that should be camel cased.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
nameof(Capitalization.CamelCase),
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.RangeVariable))),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Include an entry for _ prefixed fields (.Net style). That way features that are looking to see if
// there's a potential matching field for a particular name will find these as well.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
"CamelCaseWithUnderscore",
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field))),
new NamingStyle(Guid.NewGuid(), prefix: "_", capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Everything else should be pascal cased.
new NamingRule(
CreateDefaultSymbolSpecification(),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.PascalCase),
enforcementLevel: ReportDiagnostic.Hidden));
/// <summary>
/// Standard name rules for name suggestion/completion utilities.
/// </summary>
internal static readonly ImmutableArray<NamingRule> CompletionOfferingRules = ImmutableArray.Create(
CreateCamelCaseFieldsAndParametersRule(),
CreateEndWithAsyncRule(),
CreateGetAsyncRule(),
CreateMethodStartsWithGetRule());
private static NamingRule CreateGetAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasync", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), prefix: "Get", suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateCamelCaseFieldsAndParametersRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "camelcasefields", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
ReportDiagnostic.Info);
}
private static NamingRule CreateEndWithAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasynct", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateMethodStartsWithGetRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "startswithget", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), prefix: "Get"),
ReportDiagnostic.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 System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.NamingStyles;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Naming
{
internal static class FallbackNamingRules
{
/// <summary>
/// Standard symbol names if the user doesn't have any existing naming rules.
/// </summary>
public static readonly ImmutableArray<NamingRule> Default = ImmutableArray.Create(
// Symbols that should be camel cased.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
nameof(Capitalization.CamelCase),
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.RangeVariable))),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Include an entry for _ prefixed fields (.Net style). That way features that are looking to see if
// there's a potential matching field for a particular name will find these as well.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
"CamelCaseWithUnderscore",
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field))),
new NamingStyle(Guid.NewGuid(), prefix: "_", capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Everything else should be pascal cased.
new NamingRule(
CreateDefaultSymbolSpecification(),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.PascalCase),
enforcementLevel: ReportDiagnostic.Hidden));
/// <summary>
/// Standard name rules for name suggestion/completion utilities.
/// </summary>
internal static readonly ImmutableArray<NamingRule> CompletionOfferingRules = ImmutableArray.Create(
CreateCamelCaseFieldsAndParametersRule(),
CreateEndWithAsyncRule(),
CreateGetAsyncRule(),
CreateMethodStartsWithGetRule());
private static NamingRule CreateGetAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasync", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), prefix: "Get", suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateCamelCaseFieldsAndParametersRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "camelcasefields", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
ReportDiagnostic.Info);
}
private static NamingRule CreateEndWithAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasynct", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateMethodStartsWithGetRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "startswithget", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), prefix: "Get"),
ReportDiagnostic.Info);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/InternalUtilities/ReadOnlyUnmanagedMemoryStream.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis
{
internal sealed class ReadOnlyUnmanagedMemoryStream : Stream
{
private readonly object _memoryOwner;
private readonly IntPtr _data;
private readonly int _length;
private int _position;
public ReadOnlyUnmanagedMemoryStream(object memoryOwner, IntPtr data, int length)
{
_memoryOwner = memoryOwner;
_data = data;
_length = length;
}
public override unsafe int ReadByte()
{
if (_position == _length)
{
return -1;
}
return ((byte*)_data)[_position++];
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = Math.Min(count, _length - _position);
Marshal.Copy(_data + _position, buffer, offset, bytesRead);
_position += bytesRead;
return bytesRead;
}
public override void Flush()
{
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
return _length;
}
}
public override long Position
{
get
{
return _position;
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
long target;
try
{
switch (origin)
{
case SeekOrigin.Begin:
target = offset;
break;
case SeekOrigin.Current:
target = checked(offset + _position);
break;
case SeekOrigin.End:
target = checked(offset + _length);
break;
default:
throw new ArgumentOutOfRangeException(nameof(origin));
}
}
catch (OverflowException)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (target < 0 || target >= _length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
_position = (int)target;
return target;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis
{
internal sealed class ReadOnlyUnmanagedMemoryStream : Stream
{
private readonly object _memoryOwner;
private readonly IntPtr _data;
private readonly int _length;
private int _position;
public ReadOnlyUnmanagedMemoryStream(object memoryOwner, IntPtr data, int length)
{
_memoryOwner = memoryOwner;
_data = data;
_length = length;
}
public override unsafe int ReadByte()
{
if (_position == _length)
{
return -1;
}
return ((byte*)_data)[_position++];
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = Math.Min(count, _length - _position);
Marshal.Copy(_data + _position, buffer, offset, bytesRead);
_position += bytesRead;
return bytesRead;
}
public override void Flush()
{
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
return _length;
}
}
public override long Position
{
get
{
return _position;
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
long target;
try
{
switch (origin)
{
case SeekOrigin.Begin:
target = offset;
break;
case SeekOrigin.Current:
target = checked(offset + _position);
break;
case SeekOrigin.End:
target = checked(offset + _length);
break;
default:
throw new ArgumentOutOfRangeException(nameof(origin));
}
}
catch (OverflowException)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (target < 0 || target >= _length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
_position = (int)target;
return target;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class GeneratedTests
<Fact>
Public Sub TestUpdateWithNull()
' create type parameter with constraint clause
Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo"))))
' attempt to make variant w/o constraint clause (do not access property first)
Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing)
' correctly creates variant w/o constraint clause
Assert.Null(tp2.TypeParameterConstraintClause)
End Sub
<Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")>
Public Sub TestConstructClassBlock()
Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _
.AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y")))
Dim expectedText As String = _
"Class C(Of T)" + vbCrLf + _
" Implements X, Y" + vbCrLf + _
vbCrLf + _
"End Class"
Dim actualText = c.NormalizeWhitespace().ToFullString()
Assert.Equal(expectedText, actualText)
End Sub
<Fact()>
Public Sub TestCastExpression()
Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken))
Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing")
End Sub
<Fact()>
Public Sub TestOnErrorGoToStatement()
Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken()))
Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing")
End Sub
<Fact()>
Public Sub TestMissingToken()
For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1
If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum
Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind))
Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind))
Next k
For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1
If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum
Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind))
Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind))
Next k
End Sub
''' Bug 7983
<Fact()>
Public Sub TestParsedSyntaxTreeToString()
Dim input = " Module m1" + vbCrLf + _
"Sub Main(args As String())" + vbCrLf + _
"Sub1 ( Function(p As Integer )" + vbCrLf + _
"Sub2( )" + vbCrLf + _
"End FUNCTION)" + vbCrLf + _
"End Sub" + vbCrLf + _
"End Module "
Dim node = VisualBasicSyntaxTree.ParseText(input)
Assert.Equal(input, node.ToString())
End Sub
''' Bug 10283
<Fact()>
Public Sub Bug_10283()
Dim input = "Dim goo()"
Dim node = VisualBasicSyntaxTree.ParseText(input)
Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0)
Assert.Equal(1, arrayRankSpecifier.Rank)
Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count)
input = "Dim goo(,,,)"
node = VisualBasicSyntaxTree.ParseText(input)
arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0)
Assert.Equal(4, arrayRankSpecifier.Rank)
Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count)
End Sub
<WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")>
<Fact()>
Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace()
Dim node = SyntaxFactory.ParseCompilationUnit(" ")
Assert.True(node.HasLeadingTrivia)
Assert.Equal(1, node.GetLeadingTrivia().Count)
Assert.Equal(1, node.DescendantTrivia().Count())
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString())
End Sub
<WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")>
<Fact()>
Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace()
Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot()
Assert.True(node.HasLeadingTrivia)
Assert.Equal(1, node.GetLeadingTrivia().Count)
Assert.Equal(1, node.DescendantTrivia().Count())
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString())
End Sub
<WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")>
<Fact()>
Public Sub SyntaxTreeIsHidden_Bug13776()
Dim source = <![CDATA[
Module Program
Sub Main()
If a Then
a()
Else If b Then
#End ExternalSource
b()
#ExternalSource
Else
c()
End If
End Sub
End Module
]]>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(source)
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal)))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal)))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal)))
End Sub
<WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")>
<Fact()>
Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244()
Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement()
Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression())
Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind)
End Sub
<Fact>
Public Sub TestSeparatedListFactory_DefaultSeparators()
Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax()))
Assert.Equal(0, null1.Count)
Assert.Equal(0, null1.SeparatorCount)
Assert.Equal("", null1.ToString())
Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax)))
Assert.Equal(0, null2.Count)
Assert.Equal(0, null2.SeparatorCount)
Assert.Equal("", null2.ToString())
Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {})
Assert.Equal(0, empty1.Count)
Assert.Equal(0, empty1.SeparatorCount)
Assert.Equal("", empty1.ToString())
Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)())
Assert.Equal(0, empty2.Count)
Assert.Equal(0, empty2.SeparatorCount)
Assert.Equal("", empty2.ToString())
Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")})
Assert.Equal(1, singleton1.Count)
Assert.Equal(0, singleton1.SeparatorCount)
Assert.Equal("a", singleton1.ToString())
Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax)))
Assert.Equal(1, singleton2.Count)
Assert.Equal(0, singleton2.SeparatorCount)
Assert.Equal("x", singleton2.ToString())
Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")})
Assert.Equal(3, list1.Count)
Assert.Equal(2, list1.SeparatorCount)
Assert.Equal("a,b,c", list1.ToString())
Dim builder = New List(Of ArgumentSyntax)()
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x")))
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y")))
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z")))
Dim list2 = SyntaxFactory.SeparatedList(builder)
Assert.Equal(3, list2.Count)
Assert.Equal(2, list2.SeparatorCount)
Assert.Equal("x,y,z", list2.ToString())
End Sub
<Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")>
Public Sub FindTokenOnStartOfContinuedLine()
Dim code =
<code>
Namespace a
<TestClass> _
Public Class UnitTest1
End Class
End Namespace
</code>.Value
Dim text = SourceText.From(code)
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start)
Assert.Equal(">", token.ToString())
End Sub
<Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")>
Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue()
Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib")
Assert.True(parsedTypeName.ContainsSkippedText)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class GeneratedTests
<Fact>
Public Sub TestUpdateWithNull()
' create type parameter with constraint clause
Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo"))))
' attempt to make variant w/o constraint clause (do not access property first)
Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing)
' correctly creates variant w/o constraint clause
Assert.Null(tp2.TypeParameterConstraintClause)
End Sub
<Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")>
Public Sub TestConstructClassBlock()
Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _
.AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y")))
Dim expectedText As String = _
"Class C(Of T)" + vbCrLf + _
" Implements X, Y" + vbCrLf + _
vbCrLf + _
"End Class"
Dim actualText = c.NormalizeWhitespace().ToFullString()
Assert.Equal(expectedText, actualText)
End Sub
<Fact()>
Public Sub TestCastExpression()
Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken))
Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing")
End Sub
<Fact()>
Public Sub TestOnErrorGoToStatement()
Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken()))
Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing")
End Sub
<Fact()>
Public Sub TestMissingToken()
For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1
If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum
Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind))
Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind))
Next k
For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1
If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum
Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind))
Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind))
Next k
End Sub
''' Bug 7983
<Fact()>
Public Sub TestParsedSyntaxTreeToString()
Dim input = " Module m1" + vbCrLf + _
"Sub Main(args As String())" + vbCrLf + _
"Sub1 ( Function(p As Integer )" + vbCrLf + _
"Sub2( )" + vbCrLf + _
"End FUNCTION)" + vbCrLf + _
"End Sub" + vbCrLf + _
"End Module "
Dim node = VisualBasicSyntaxTree.ParseText(input)
Assert.Equal(input, node.ToString())
End Sub
''' Bug 10283
<Fact()>
Public Sub Bug_10283()
Dim input = "Dim goo()"
Dim node = VisualBasicSyntaxTree.ParseText(input)
Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0)
Assert.Equal(1, arrayRankSpecifier.Rank)
Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count)
input = "Dim goo(,,,)"
node = VisualBasicSyntaxTree.ParseText(input)
arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0)
Assert.Equal(4, arrayRankSpecifier.Rank)
Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count)
End Sub
<WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")>
<Fact()>
Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace()
Dim node = SyntaxFactory.ParseCompilationUnit(" ")
Assert.True(node.HasLeadingTrivia)
Assert.Equal(1, node.GetLeadingTrivia().Count)
Assert.Equal(1, node.DescendantTrivia().Count())
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString())
End Sub
<WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")>
<Fact()>
Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace()
Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot()
Assert.True(node.HasLeadingTrivia)
Assert.Equal(1, node.GetLeadingTrivia().Count)
Assert.Equal(1, node.DescendantTrivia().Count())
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString())
End Sub
<WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")>
<Fact()>
Public Sub SyntaxTreeIsHidden_Bug13776()
Dim source = <![CDATA[
Module Program
Sub Main()
If a Then
a()
Else If b Then
#End ExternalSource
b()
#ExternalSource
Else
c()
End If
End Sub
End Module
]]>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(source)
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal)))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal)))
Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal)))
End Sub
<WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")>
<Fact()>
Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244()
Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement()
Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression())
Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind)
End Sub
<Fact>
Public Sub TestSeparatedListFactory_DefaultSeparators()
Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax()))
Assert.Equal(0, null1.Count)
Assert.Equal(0, null1.SeparatorCount)
Assert.Equal("", null1.ToString())
Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax)))
Assert.Equal(0, null2.Count)
Assert.Equal(0, null2.SeparatorCount)
Assert.Equal("", null2.ToString())
Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {})
Assert.Equal(0, empty1.Count)
Assert.Equal(0, empty1.SeparatorCount)
Assert.Equal("", empty1.ToString())
Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)())
Assert.Equal(0, empty2.Count)
Assert.Equal(0, empty2.SeparatorCount)
Assert.Equal("", empty2.ToString())
Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")})
Assert.Equal(1, singleton1.Count)
Assert.Equal(0, singleton1.SeparatorCount)
Assert.Equal("a", singleton1.ToString())
Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax)))
Assert.Equal(1, singleton2.Count)
Assert.Equal(0, singleton2.SeparatorCount)
Assert.Equal("x", singleton2.ToString())
Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")})
Assert.Equal(3, list1.Count)
Assert.Equal(2, list1.SeparatorCount)
Assert.Equal("a,b,c", list1.ToString())
Dim builder = New List(Of ArgumentSyntax)()
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x")))
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y")))
builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z")))
Dim list2 = SyntaxFactory.SeparatedList(builder)
Assert.Equal(3, list2.Count)
Assert.Equal(2, list2.SeparatorCount)
Assert.Equal("x,y,z", list2.ToString())
End Sub
<Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")>
Public Sub FindTokenOnStartOfContinuedLine()
Dim code =
<code>
Namespace a
<TestClass> _
Public Class UnitTest1
End Class
End Namespace
</code>.Value
Dim text = SourceText.From(code)
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start)
Assert.Equal(">", token.ToString())
End Sub
<Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")>
Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue()
Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib")
Assert.True(parsedTypeName.ContainsSkippedText)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/SignatureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers
{
[CompilerTrait(CompilerFeature.ModuleInitializers)]
public sealed class SignatureTests : CSharpTestBase
{
private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9;
[Fact]
public void MustNotBeInstanceMethod()
{
string source = @"
using System.Runtime.CompilerServices;
class C
{
[ModuleInitializer]
internal void M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeInstanceMethodInInterface()
{
string source = @"
using System.Runtime.CompilerServices;
interface i
{
[ModuleInitializer]
internal void M1();
[ModuleInitializer]
internal void M2() { }
}
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M1' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M1").WithLocation(6, 6),
// (9,6): error CS8815: Module initializer method 'M2' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M2").WithLocation(9, 6)
);
}
[Fact]
public void MustNotHaveParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(object p) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotHaveOptionalParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(object p = null) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotHaveParamsArrayParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(params object[] p) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotReturnAValue()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static object M() => null;
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MayBeAsyncVoid()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static async void M() => Console.WriteLine(""C.M"");
}
class Program
{
static void Main() => Console.WriteLine(""Program.Main"");
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @"
C.M
Program.Main");
}
[Fact]
public void MayNotReturnAwaitableWithVoidResult()
{
string source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
static class C
{
[ModuleInitializer]
internal static async Task M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(7, 6),
// (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// internal static async Task M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(8, 32));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers
{
[CompilerTrait(CompilerFeature.ModuleInitializers)]
public sealed class SignatureTests : CSharpTestBase
{
private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9;
[Fact]
public void MustNotBeInstanceMethod()
{
string source = @"
using System.Runtime.CompilerServices;
class C
{
[ModuleInitializer]
internal void M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeInstanceMethodInInterface()
{
string source = @"
using System.Runtime.CompilerServices;
interface i
{
[ModuleInitializer]
internal void M1();
[ModuleInitializer]
internal void M2() { }
}
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M1' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M1").WithLocation(6, 6),
// (9,6): error CS8815: Module initializer method 'M2' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M2").WithLocation(9, 6)
);
}
[Fact]
public void MustNotHaveParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(object p) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotHaveOptionalParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(object p = null) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotHaveParamsArrayParameters()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static void M(params object[] p) { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotReturnAValue()
{
string source = @"
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static object M() => null;
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MayBeAsyncVoid()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
static class C
{
[ModuleInitializer]
internal static async void M() => Console.WriteLine(""C.M"");
}
class Program
{
static void Main() => Console.WriteLine(""Program.Main"");
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @"
C.M
Program.Main");
}
[Fact]
public void MayNotReturnAwaitableWithVoidResult()
{
string source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
static class C
{
[ModuleInitializer]
internal static async Task M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void'
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(7, 6),
// (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// internal static async Task M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(8, 32));
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Core/Portable/Serialization/SerializationExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
internal static class SerializationExtensions
{
public static WellKnownSynchronizationKind GetWellKnownSynchronizationKind(this object value)
=> value switch
{
SolutionStateChecksums _ => WellKnownSynchronizationKind.SolutionState,
ProjectStateChecksums _ => WellKnownSynchronizationKind.ProjectState,
DocumentStateChecksums _ => WellKnownSynchronizationKind.DocumentState,
ChecksumCollection _ => WellKnownSynchronizationKind.ChecksumCollection,
SolutionInfo.SolutionAttributes _ => WellKnownSynchronizationKind.SolutionAttributes,
ProjectInfo.ProjectAttributes _ => WellKnownSynchronizationKind.ProjectAttributes,
DocumentInfo.DocumentAttributes _ => WellKnownSynchronizationKind.DocumentAttributes,
CompilationOptions _ => WellKnownSynchronizationKind.CompilationOptions,
ParseOptions _ => WellKnownSynchronizationKind.ParseOptions,
ProjectReference _ => WellKnownSynchronizationKind.ProjectReference,
MetadataReference _ => WellKnownSynchronizationKind.MetadataReference,
AnalyzerReference _ => WellKnownSynchronizationKind.AnalyzerReference,
SerializableSourceText _ => WellKnownSynchronizationKind.SerializableSourceText,
SourceText _ => WellKnownSynchronizationKind.SourceText,
OptionSet _ => WellKnownSynchronizationKind.OptionSet,
SourceGeneratedDocumentIdentity _ => WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity,
_ => throw ExceptionUtilities.UnexpectedValue(value),
};
public static CompilationOptions FixUpCompilationOptions(this ProjectInfo.ProjectAttributes info, CompilationOptions compilationOptions)
{
return compilationOptions.WithXmlReferenceResolver(GetXmlResolver(info.FilePath))
.WithStrongNameProvider(new DesktopStrongNameProvider(GetStrongNameKeyPaths(info)));
}
private static XmlFileResolver GetXmlResolver(string? filePath)
{
// Given filePath can be any arbitrary string project is created with.
// for primary solution in host such as VSWorkspace, ETA or MSBuildWorkspace
// filePath will point to actual file on disk, but in memory solultion, or
// one from AdhocWorkspace and etc, FilePath can be a random string.
// Make sure we return only if given filePath is in right form.
if (!PathUtilities.IsAbsolute(filePath))
{
// xmlFileResolver can only deal with absolute path
// return Default
return XmlFileResolver.Default;
}
return new XmlFileResolver(PathUtilities.GetDirectoryName(filePath));
}
private static ImmutableArray<string> GetStrongNameKeyPaths(ProjectInfo.ProjectAttributes info)
{
// Given FilePath/OutputFilePath can be any arbitrary strings project is created with.
// for primary solution in host such as VSWorkspace, ETA or MSBuildWorkspace
// filePath will point to actual file on disk, but in memory solultion, or
// one from AdhocWorkspace and etc, FilePath/OutputFilePath can be a random string.
// Make sure we return only if given filePath is in right form.
if (info.FilePath == null && info.OutputFilePath == null)
{
// return empty since that is what IDE does for this case
// see AbstractProject.GetStrongNameKeyPaths
return ImmutableArray<string>.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
if (PathUtilities.IsAbsolute(info.FilePath))
{
// desktop strong name provider only knows how to deal with absolute path
builder.Add(PathUtilities.GetDirectoryName(info.FilePath)!);
}
if (PathUtilities.IsAbsolute(info.OutputFilePath))
{
// desktop strong name provider only knows how to deal with absolute path
builder.Add(PathUtilities.GetDirectoryName(info.OutputFilePath)!);
}
return builder.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.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
internal static class SerializationExtensions
{
public static WellKnownSynchronizationKind GetWellKnownSynchronizationKind(this object value)
=> value switch
{
SolutionStateChecksums _ => WellKnownSynchronizationKind.SolutionState,
ProjectStateChecksums _ => WellKnownSynchronizationKind.ProjectState,
DocumentStateChecksums _ => WellKnownSynchronizationKind.DocumentState,
ChecksumCollection _ => WellKnownSynchronizationKind.ChecksumCollection,
SolutionInfo.SolutionAttributes _ => WellKnownSynchronizationKind.SolutionAttributes,
ProjectInfo.ProjectAttributes _ => WellKnownSynchronizationKind.ProjectAttributes,
DocumentInfo.DocumentAttributes _ => WellKnownSynchronizationKind.DocumentAttributes,
CompilationOptions _ => WellKnownSynchronizationKind.CompilationOptions,
ParseOptions _ => WellKnownSynchronizationKind.ParseOptions,
ProjectReference _ => WellKnownSynchronizationKind.ProjectReference,
MetadataReference _ => WellKnownSynchronizationKind.MetadataReference,
AnalyzerReference _ => WellKnownSynchronizationKind.AnalyzerReference,
SerializableSourceText _ => WellKnownSynchronizationKind.SerializableSourceText,
SourceText _ => WellKnownSynchronizationKind.SourceText,
OptionSet _ => WellKnownSynchronizationKind.OptionSet,
SourceGeneratedDocumentIdentity _ => WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity,
_ => throw ExceptionUtilities.UnexpectedValue(value),
};
public static CompilationOptions FixUpCompilationOptions(this ProjectInfo.ProjectAttributes info, CompilationOptions compilationOptions)
{
return compilationOptions.WithXmlReferenceResolver(GetXmlResolver(info.FilePath))
.WithStrongNameProvider(new DesktopStrongNameProvider(GetStrongNameKeyPaths(info)));
}
private static XmlFileResolver GetXmlResolver(string? filePath)
{
// Given filePath can be any arbitrary string project is created with.
// for primary solution in host such as VSWorkspace, ETA or MSBuildWorkspace
// filePath will point to actual file on disk, but in memory solultion, or
// one from AdhocWorkspace and etc, FilePath can be a random string.
// Make sure we return only if given filePath is in right form.
if (!PathUtilities.IsAbsolute(filePath))
{
// xmlFileResolver can only deal with absolute path
// return Default
return XmlFileResolver.Default;
}
return new XmlFileResolver(PathUtilities.GetDirectoryName(filePath));
}
private static ImmutableArray<string> GetStrongNameKeyPaths(ProjectInfo.ProjectAttributes info)
{
// Given FilePath/OutputFilePath can be any arbitrary strings project is created with.
// for primary solution in host such as VSWorkspace, ETA or MSBuildWorkspace
// filePath will point to actual file on disk, but in memory solultion, or
// one from AdhocWorkspace and etc, FilePath/OutputFilePath can be a random string.
// Make sure we return only if given filePath is in right form.
if (info.FilePath == null && info.OutputFilePath == null)
{
// return empty since that is what IDE does for this case
// see AbstractProject.GetStrongNameKeyPaths
return ImmutableArray<string>.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
if (PathUtilities.IsAbsolute(info.FilePath))
{
// desktop strong name provider only knows how to deal with absolute path
builder.Add(PathUtilities.GetDirectoryName(info.FilePath)!);
}
if (PathUtilities.IsAbsolute(info.OutputFilePath))
{
// desktop strong name provider only knows how to deal with absolute path
builder.Add(PathUtilities.GetDirectoryName(info.OutputFilePath)!);
}
return builder.ToImmutableAndFree();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/TupleTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Scanner/ScannerInterpolatedString.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
Private Function ScanInterpolatedStringPunctuation() As SyntaxToken
If Not CanGet() Then
Return MakeEndOfInterpolatedStringToken()
End If
Dim kind As SyntaxKind
Dim leadingTriviaLength = GetWhitespaceLength(0)
Dim offset = leadingTriviaLength
Dim length As Integer
If Not CanGet(offset) Then
Return MakeEndOfInterpolatedStringToken()
End If
Dim c = Peek(offset)
' This should only ever happen for $" or }
Debug.Assert(leadingTriviaLength = 0 OrElse c = "$"c OrElse c = FULLWIDTH_DOLLAR_SIGN OrElse IsRightCurlyBracket(c))
' Another } may follow the close brace of an interpolation if the interpolation lacked a format clause.
' This is because the normal escaping rules only apply when parsing the format string.
Debug.Assert(Not CanGet(offset + 1) OrElse Peek(offset + 1) <> c OrElse Not (IsLeftCurlyBracket(c) OrElse IsDoubleQuote(c)), "Escape sequence not detected.")
Dim scanTrailingTrivia As Boolean
Select Case c
Case "$"c, FULLWIDTH_DOLLAR_SIGN
If CanGet(offset + 1) AndAlso IsDoubleQuote(Peek(offset + 1)) Then
kind = SyntaxKind.DollarSignDoubleQuoteToken
length = 2
scanTrailingTrivia = False ' Trailing whitespace should be scanned as interpolated string text.
Else
' We should only reach this point if the parser already detected a full $" token and we're now rescanning.
Throw ExceptionUtilities.Unreachable
End If
Case "{"c, FULLWIDTH_LEFT_CURLY_BRACKET
kind = SyntaxKind.OpenBraceToken
length = 1
scanTrailingTrivia = True
Case ","c, FULLWIDTH_COMMA
kind = SyntaxKind.CommaToken
length = 1
scanTrailingTrivia = True
Case ":"c, FULLWIDTH_COLON
kind = SyntaxKind.ColonToken
length = 1
scanTrailingTrivia = False ' Trailing trivia should be scanned as part of the format string text.
Case "}"c, FULLWIDTH_RIGHT_CURLY_BRACKET
kind = SyntaxKind.CloseBraceToken
length = 1
scanTrailingTrivia = False ' Trailing whitespace should be scanned as interpolated string text.
Case Else
If IsDoubleQuote(c) Then
Debug.Assert(Not CanGet(offset + 1) OrElse Not IsDoubleQuote(Peek(offset + 1)))
kind = SyntaxKind.DoubleQuoteToken
length = 1
scanTrailingTrivia = True
Else
Return MakeEndOfInterpolatedStringToken()
End If
End Select
Dim leadingTrivia = ScanWhitespace(leadingTriviaLength)
Dim text = GetText(length)
Dim trailingTrivia As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = If(scanTrailingTrivia, ScanSingleLineTrivia(), Nothing)
Return MakePunctuationToken(kind, text, leadingTrivia, trailingTrivia.Node)
End Function
Private Function ScanInterpolatedStringContent() As SyntaxToken
If IsInterpolatedStringPunctuation() Then
Return ScanInterpolatedStringPunctuation()
Else
Return ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia:=False)
End If
End Function
Private Function ScanInterpolatedStringFormatString() As SyntaxToken
If IsInterpolatedStringPunctuation() Then
Return ScanInterpolatedStringPunctuation()
Else
Return ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia:=True)
End If
End Function
Private Function IsInterpolatedStringPunctuation(Optional offset As Integer = 0) As Boolean
If Not CanGet(offset) Then Return False
Dim c = Peek(offset)
If IsLeftCurlyBracket(c) Then
Return Not CanGet(offset + 1) OrElse Not IsLeftCurlyBracket(Peek(offset + 1))
ElseIf IsRightCurlyBracket(c) Then
Return Not CanGet(offset + 1) OrElse Not IsRightCurlyBracket(Peek(offset + 1))
ElseIf IsDoubleQuote(c)
'A subtle difference between this case and the one above.
' In both interpolated and literal strings the two quote characters used in an escape sequence don't have to match.
' It's enough that the next character is *a* quote char. It doesn't have to be the same quote.
' If we want to preserve consistency the quotes need to be special cased.
Return Not CanGet(offset + 1) OrElse Not IsDoubleQuote(Peek(offset + 1))
Else
Return False
End If
End Function
Private Function ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia As Boolean) As SyntaxToken
If Not CanGet() Then Return MakeEndOfInterpolatedStringToken()
Dim offset = 0
Dim pendingWhitespace = 0
Dim valueBuilder = GetScratch()
Do While CanGet(offset)
Dim c = Peek(offset)
' Any combination of fullwidth and ASCII curly braces of the same direction is an escaping sequence for the corresponding ASCII curly brace.
' We insert that curly brace doubled and because this is the escaping sequence understood by String.Format, that will be replaced by a single brace.
' This is deliberate design and it aligns with existing rules for double quote escaping in strings.
If IsLeftCurlyBracket(c) Then
If CanGet(offset + 1) AndAlso IsLeftCurlyBracket(Peek(offset + 1)) Then
' This is an escape sequence.
valueBuilder.Append("{{")
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsRightCurlyBracket(c) Then
If CanGet(offset + 1) AndAlso IsRightCurlyBracket(Peek(offset + 1)) Then
' This is an escape sequence.
valueBuilder.Append("}}")
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsDoubleQuote(c)
If CanGet(offset + 1) AndAlso IsDoubleQuote(Peek(offset + 1)) Then
' This is a VB double quote escape. Oddly enough this logic allows mixing and matching of
' smart and dumb double quotes in any order. Regardless we always emit as a standard double quote.
' This is consistent with their handling in string literals.
valueBuilder.Append(""""c)
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsNewLine(c) AndAlso scanTrailingWhitespaceAsTrivia
Exit Do
ElseIf IsWhitespace(c) AndAlso scanTrailingWhitespaceAsTrivia
valueBuilder.Append(c)
offset += 1
pendingWhitespace += 1
Continue Do
Else
valueBuilder.Append(c)
offset += 1
pendingWhitespace = 0
End If
Loop
' There was trailing whitespace.
If pendingWhitespace > 0 Then
offset -= pendingWhitespace
valueBuilder.Length -= pendingWhitespace
End If
Dim text = If(offset > 0, GetTextNotInterned(offset), String.Empty)
' PERF: It's common for the text and the 'value' to be identical. If so, try to unify the
' two strings.
Dim value = GetScratchText(valueBuilder, text)
Return SyntaxFactory.InterpolatedStringTextToken(text, value, Nothing, ScanWhitespace(pendingWhitespace))
End Function
Private Function MakeEndOfInterpolatedStringToken() As SyntaxToken
Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfInterpolatedStringToken, Nothing, String.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.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
Private Function ScanInterpolatedStringPunctuation() As SyntaxToken
If Not CanGet() Then
Return MakeEndOfInterpolatedStringToken()
End If
Dim kind As SyntaxKind
Dim leadingTriviaLength = GetWhitespaceLength(0)
Dim offset = leadingTriviaLength
Dim length As Integer
If Not CanGet(offset) Then
Return MakeEndOfInterpolatedStringToken()
End If
Dim c = Peek(offset)
' This should only ever happen for $" or }
Debug.Assert(leadingTriviaLength = 0 OrElse c = "$"c OrElse c = FULLWIDTH_DOLLAR_SIGN OrElse IsRightCurlyBracket(c))
' Another } may follow the close brace of an interpolation if the interpolation lacked a format clause.
' This is because the normal escaping rules only apply when parsing the format string.
Debug.Assert(Not CanGet(offset + 1) OrElse Peek(offset + 1) <> c OrElse Not (IsLeftCurlyBracket(c) OrElse IsDoubleQuote(c)), "Escape sequence not detected.")
Dim scanTrailingTrivia As Boolean
Select Case c
Case "$"c, FULLWIDTH_DOLLAR_SIGN
If CanGet(offset + 1) AndAlso IsDoubleQuote(Peek(offset + 1)) Then
kind = SyntaxKind.DollarSignDoubleQuoteToken
length = 2
scanTrailingTrivia = False ' Trailing whitespace should be scanned as interpolated string text.
Else
' We should only reach this point if the parser already detected a full $" token and we're now rescanning.
Throw ExceptionUtilities.Unreachable
End If
Case "{"c, FULLWIDTH_LEFT_CURLY_BRACKET
kind = SyntaxKind.OpenBraceToken
length = 1
scanTrailingTrivia = True
Case ","c, FULLWIDTH_COMMA
kind = SyntaxKind.CommaToken
length = 1
scanTrailingTrivia = True
Case ":"c, FULLWIDTH_COLON
kind = SyntaxKind.ColonToken
length = 1
scanTrailingTrivia = False ' Trailing trivia should be scanned as part of the format string text.
Case "}"c, FULLWIDTH_RIGHT_CURLY_BRACKET
kind = SyntaxKind.CloseBraceToken
length = 1
scanTrailingTrivia = False ' Trailing whitespace should be scanned as interpolated string text.
Case Else
If IsDoubleQuote(c) Then
Debug.Assert(Not CanGet(offset + 1) OrElse Not IsDoubleQuote(Peek(offset + 1)))
kind = SyntaxKind.DoubleQuoteToken
length = 1
scanTrailingTrivia = True
Else
Return MakeEndOfInterpolatedStringToken()
End If
End Select
Dim leadingTrivia = ScanWhitespace(leadingTriviaLength)
Dim text = GetText(length)
Dim trailingTrivia As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = If(scanTrailingTrivia, ScanSingleLineTrivia(), Nothing)
Return MakePunctuationToken(kind, text, leadingTrivia, trailingTrivia.Node)
End Function
Private Function ScanInterpolatedStringContent() As SyntaxToken
If IsInterpolatedStringPunctuation() Then
Return ScanInterpolatedStringPunctuation()
Else
Return ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia:=False)
End If
End Function
Private Function ScanInterpolatedStringFormatString() As SyntaxToken
If IsInterpolatedStringPunctuation() Then
Return ScanInterpolatedStringPunctuation()
Else
Return ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia:=True)
End If
End Function
Private Function IsInterpolatedStringPunctuation(Optional offset As Integer = 0) As Boolean
If Not CanGet(offset) Then Return False
Dim c = Peek(offset)
If IsLeftCurlyBracket(c) Then
Return Not CanGet(offset + 1) OrElse Not IsLeftCurlyBracket(Peek(offset + 1))
ElseIf IsRightCurlyBracket(c) Then
Return Not CanGet(offset + 1) OrElse Not IsRightCurlyBracket(Peek(offset + 1))
ElseIf IsDoubleQuote(c)
'A subtle difference between this case and the one above.
' In both interpolated and literal strings the two quote characters used in an escape sequence don't have to match.
' It's enough that the next character is *a* quote char. It doesn't have to be the same quote.
' If we want to preserve consistency the quotes need to be special cased.
Return Not CanGet(offset + 1) OrElse Not IsDoubleQuote(Peek(offset + 1))
Else
Return False
End If
End Function
Private Function ScanInterpolatedStringText(scanTrailingWhitespaceAsTrivia As Boolean) As SyntaxToken
If Not CanGet() Then Return MakeEndOfInterpolatedStringToken()
Dim offset = 0
Dim pendingWhitespace = 0
Dim valueBuilder = GetScratch()
Do While CanGet(offset)
Dim c = Peek(offset)
' Any combination of fullwidth and ASCII curly braces of the same direction is an escaping sequence for the corresponding ASCII curly brace.
' We insert that curly brace doubled and because this is the escaping sequence understood by String.Format, that will be replaced by a single brace.
' This is deliberate design and it aligns with existing rules for double quote escaping in strings.
If IsLeftCurlyBracket(c) Then
If CanGet(offset + 1) AndAlso IsLeftCurlyBracket(Peek(offset + 1)) Then
' This is an escape sequence.
valueBuilder.Append("{{")
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsRightCurlyBracket(c) Then
If CanGet(offset + 1) AndAlso IsRightCurlyBracket(Peek(offset + 1)) Then
' This is an escape sequence.
valueBuilder.Append("}}")
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsDoubleQuote(c)
If CanGet(offset + 1) AndAlso IsDoubleQuote(Peek(offset + 1)) Then
' This is a VB double quote escape. Oddly enough this logic allows mixing and matching of
' smart and dumb double quotes in any order. Regardless we always emit as a standard double quote.
' This is consistent with their handling in string literals.
valueBuilder.Append(""""c)
offset += 2
pendingWhitespace = 0
Continue Do
End If
Exit Do
ElseIf IsNewLine(c) AndAlso scanTrailingWhitespaceAsTrivia
Exit Do
ElseIf IsWhitespace(c) AndAlso scanTrailingWhitespaceAsTrivia
valueBuilder.Append(c)
offset += 1
pendingWhitespace += 1
Continue Do
Else
valueBuilder.Append(c)
offset += 1
pendingWhitespace = 0
End If
Loop
' There was trailing whitespace.
If pendingWhitespace > 0 Then
offset -= pendingWhitespace
valueBuilder.Length -= pendingWhitespace
End If
Dim text = If(offset > 0, GetTextNotInterned(offset), String.Empty)
' PERF: It's common for the text and the 'value' to be identical. If so, try to unify the
' two strings.
Dim value = GetScratchText(valueBuilder, text)
Return SyntaxFactory.InterpolatedStringTextToken(text, value, Nothing, ScanWhitespace(pendingWhitespace))
End Function
Private Function MakeEndOfInterpolatedStringToken() As SyntaxToken
Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfInterpolatedStringToken, Nothing, String.Empty)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/Core/Impl/Options/GridOptionPreviewControl.xaml | <options:AbstractOptionPageControl
x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.Options.GridOptionPreviewControl"
x:ClassModifier="internal"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options"
xmlns:converters="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:options="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options"
xmlns:imaging="clr-namespace:Microsoft.VisualStudio.Imaging;assembly=Microsoft.VisualStudio.Imaging"
xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.14.0"
xmlns:imagingPlatformUI="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Imaging"
mc:Ignorable="d" d:DesignHeight="279" d:DesignWidth="514">
<Grid>
<Grid.Resources>
<options:ColumnToTabStopConverter x:Key="ColumnToTabStopConverter" />
<Style x:Key="DataGridStyle" TargetType="DataGrid">
<Setter Property="CellStyle">
<Setter.Value>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="IsTabStop"
Value="{Binding
Path=Column,
Converter={StaticResource ColumnToTabStopConverter},
RelativeSource={RelativeSource Self}}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
<Thickness x:Key="cellPadding">8 0 8 0</Thickness>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<converters:MarginConverter x:Key="MarginConverter" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<options:CodeStyleNoticeTextBlock Grid.Row="0" Margin="5 0 5 0" />
<Button
Grid.Row="1"
Name="GenerateEditorConfigButton"
Click="Generate_Save_EditorConfig"
Content="{x:Static local:GridOptionPreviewControl.GenerateEditorConfigFileFromSettingsText}"
HorizontalAlignment="Left"
Margin="0,5,0,0"
VerticalAlignment="Center"
Padding="5"/>
<DataGrid
Grid.Row="2"
x:Uid="CodeStyleContent"
x:Name="CodeStyleMembers"
Margin="0,5,0,0"
ItemsSource="{Binding CodeStyleItems, Mode=OneWay}"
AutoGenerateColumns="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserResizeRows="False"
CanUserResizeColumns="False"
IsReadOnly="True"
BorderThickness="1"
BorderBrush="Gray"
RowHeaderWidth="0"
GridLinesVisibility="None"
VerticalAlignment="Stretch"
SelectionMode="Single"
HorizontalAlignment="Stretch"
Style="{StaticResource ResourceKey=DataGridStyle}"
SelectionChanged="Options_SelectionChanged"
PreviewKeyDown="Options_PreviewKeyDown">
<DataGrid.Resources>
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<StackPanel>
<TextBlock Margin="5" Text="{Binding Name}"/>
<ItemsPresenter/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
<DataGrid.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
<GroupStyle.Panel>
<ItemsPanelTemplate>
<DataGridRowsPresenter/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<DataGridTemplateColumn
x:Name="description"
Header="{x:Static local:GridOptionPreviewControl.DescriptionHeader}"
Width="4.5*"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<local:TextBlockWithDataItemControlType
Text="{Binding Description, Mode=OneWay}"
Margin="{Binding DescriptionMargin, Converter={StaticResource MarginConverter}}"
Padding="{StaticResource ResourceKey=cellPadding}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
TextWrapping="Wrap"
AutomationProperties.Name="{Binding GroupNameAndDescription}"
Focusable="True"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
x:Name="preference"
Header="{x:Static local:GridOptionPreviewControl.PreferenceHeader}"
Width="3*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding Preferences}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedPreference, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
x:Name="severity"
Header="{x:Static local:GridOptionPreviewControl.SeverityHeader}"
Width="2.5*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding NotificationPreferences}"
SelectedItem="{Binding SelectedNotificationPreference,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Visibility="{Binding NotificationsAvailable, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<imaging:CrispImage
Height="16"
Width="16"
Moniker="{Binding Moniker}"
Grid.Column="0"/>
<TextBlock
Margin="5, 0, 0, 0"
Text="{Binding Notification}"
Grid.Column="1"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<GridSplitter Grid.Row="3" HorizontalAlignment="Stretch"></GridSplitter>
<Border Grid.Row="4" BorderBrush="Gray" BorderThickness="1">
<ContentControl Name="EditorControl" Content="{Binding TextViewHost, Mode=OneWay}" Focusable="False"></ContentControl>
</Border>
</Grid>
</options:AbstractOptionPageControl> | <options:AbstractOptionPageControl
x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.Options.GridOptionPreviewControl"
x:ClassModifier="internal"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options"
xmlns:converters="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:options="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options"
xmlns:imaging="clr-namespace:Microsoft.VisualStudio.Imaging;assembly=Microsoft.VisualStudio.Imaging"
xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.14.0"
xmlns:imagingPlatformUI="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Imaging"
mc:Ignorable="d" d:DesignHeight="279" d:DesignWidth="514">
<Grid>
<Grid.Resources>
<options:ColumnToTabStopConverter x:Key="ColumnToTabStopConverter" />
<Style x:Key="DataGridStyle" TargetType="DataGrid">
<Setter Property="CellStyle">
<Setter.Value>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="IsTabStop"
Value="{Binding
Path=Column,
Converter={StaticResource ColumnToTabStopConverter},
RelativeSource={RelativeSource Self}}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
<Thickness x:Key="cellPadding">8 0 8 0</Thickness>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<converters:MarginConverter x:Key="MarginConverter" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<options:CodeStyleNoticeTextBlock Grid.Row="0" Margin="5 0 5 0" />
<Button
Grid.Row="1"
Name="GenerateEditorConfigButton"
Click="Generate_Save_EditorConfig"
Content="{x:Static local:GridOptionPreviewControl.GenerateEditorConfigFileFromSettingsText}"
HorizontalAlignment="Left"
Margin="0,5,0,0"
VerticalAlignment="Center"
Padding="5"/>
<DataGrid
Grid.Row="2"
x:Uid="CodeStyleContent"
x:Name="CodeStyleMembers"
Margin="0,5,0,0"
ItemsSource="{Binding CodeStyleItems, Mode=OneWay}"
AutoGenerateColumns="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserResizeRows="False"
CanUserResizeColumns="False"
IsReadOnly="True"
BorderThickness="1"
BorderBrush="Gray"
RowHeaderWidth="0"
GridLinesVisibility="None"
VerticalAlignment="Stretch"
SelectionMode="Single"
HorizontalAlignment="Stretch"
Style="{StaticResource ResourceKey=DataGridStyle}"
SelectionChanged="Options_SelectionChanged"
PreviewKeyDown="Options_PreviewKeyDown">
<DataGrid.Resources>
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<StackPanel>
<TextBlock Margin="5" Text="{Binding Name}"/>
<ItemsPresenter/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
<DataGrid.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
<GroupStyle.Panel>
<ItemsPanelTemplate>
<DataGridRowsPresenter/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<DataGridTemplateColumn
x:Name="description"
Header="{x:Static local:GridOptionPreviewControl.DescriptionHeader}"
Width="4.5*"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<local:TextBlockWithDataItemControlType
Text="{Binding Description, Mode=OneWay}"
Margin="{Binding DescriptionMargin, Converter={StaticResource MarginConverter}}"
Padding="{StaticResource ResourceKey=cellPadding}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
TextWrapping="Wrap"
AutomationProperties.Name="{Binding GroupNameAndDescription}"
Focusable="True"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
x:Name="preference"
Header="{x:Static local:GridOptionPreviewControl.PreferenceHeader}"
Width="3*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding Preferences}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedPreference, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
x:Name="severity"
Header="{x:Static local:GridOptionPreviewControl.SeverityHeader}"
Width="2.5*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding NotificationPreferences}"
SelectedItem="{Binding SelectedNotificationPreference,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Visibility="{Binding NotificationsAvailable, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<imaging:CrispImage
Height="16"
Width="16"
Moniker="{Binding Moniker}"
Grid.Column="0"/>
<TextBlock
Margin="5, 0, 0, 0"
Text="{Binding Notification}"
Grid.Column="1"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<GridSplitter Grid.Row="3" HorizontalAlignment="Stretch"></GridSplitter>
<Border Grid.Row="4" BorderBrush="Gray" BorderThickness="1">
<ContentControl Name="EditorControl" Content="{Binding TextViewHost, Mode=OneWay}" Focusable="False"></ContentControl>
</Border>
</Grid>
</options:AbstractOptionPageControl> | -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Remote/Core/IRemoteHostService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteHostService
{
void InitializeGlobalState(int uiCultureLCID, int cultureLCID, CancellationToken cancellationToken);
void InitializeTelemetrySession(int hostProcessId, string serializedSession, CancellationToken cancellationToken);
/// <summary>
/// This is only for debugging
///
/// this lets remote side to set same logging options as VS side
/// </summary>
void SetLoggingFunctionIds(List<string> loggerTypes, List<string> functionIds, 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.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteHostService
{
void InitializeGlobalState(int uiCultureLCID, int cultureLCID, CancellationToken cancellationToken);
void InitializeTelemetrySession(int hostProcessId, string serializedSession, CancellationToken cancellationToken);
/// <summary>
/// This is only for debugging
///
/// this lets remote side to set same logging options as VS side
/// </summary>
void SetLoggingFunctionIds(List<string> loggerTypes, List<string> functionIds, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/FlowAnalysis/CSharpDataFlowAnalysis.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This class implements the region data flow analysis operations. Region data flow analysis
/// provides information how data flows into and out of a region. The analysis is done lazily.
/// When created, it performs no analysis, but simply caches the arguments. Then, the first time
/// one of the analysis results is used it computes that one result and caches it. Each result
/// is computed using a custom algorithm.
/// </summary>
internal class CSharpDataFlowAnalysis : DataFlowAnalysis
{
private readonly RegionAnalysisContext _context;
private ImmutableArray<ISymbol> _variablesDeclared;
private HashSet<Symbol> _unassignedVariables;
private ImmutableArray<ISymbol> _dataFlowsIn;
private ImmutableArray<ISymbol> _dataFlowsOut;
private ImmutableArray<ISymbol> _definitelyAssignedOnEntry;
private ImmutableArray<ISymbol> _definitelyAssignedOnExit;
private ImmutableArray<ISymbol> _alwaysAssigned;
private ImmutableArray<ISymbol> _readInside;
private ImmutableArray<ISymbol> _writtenInside;
private ImmutableArray<ISymbol> _readOutside;
private ImmutableArray<ISymbol> _writtenOutside;
private ImmutableArray<ISymbol> _captured;
private ImmutableArray<IMethodSymbol> _usedLocalFunctions;
private ImmutableArray<ISymbol> _capturedInside;
private ImmutableArray<ISymbol> _capturedOutside;
private ImmutableArray<ISymbol> _unsafeAddressTaken;
private HashSet<PrefixUnaryExpressionSyntax> _unassignedVariableAddressOfSyntaxes;
private bool? _succeeded;
internal CSharpDataFlowAnalysis(RegionAnalysisContext context)
{
_context = context;
}
/// <summary>
/// A collection of the local variables that are declared within the region. Note that the region must be
/// bounded by a method's body or a field's initializer, so method parameter symbols are never included
/// in the result, but lambda parameters might appear in the result.
/// </summary>
public override ImmutableArray<ISymbol> VariablesDeclared
{
// Variables declared in the region is computed by a simple scan.
// ISSUE: are these only variables declared at the top level in the region,
// or are we to include variables declared in deeper scopes within the region?
get
{
if (_variablesDeclared.IsDefault)
{
var result = Succeeded
? Normalize(VariablesDeclaredWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _variablesDeclared, result);
}
return _variablesDeclared;
}
}
private HashSet<Symbol> UnassignedVariables
{
get
{
if (_unassignedVariables == null)
{
var result = Succeeded
? UnassignedVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode)
: new HashSet<Symbol>();
Interlocked.CompareExchange(ref _unassignedVariables, result, null);
}
return _unassignedVariables;
}
}
/// <summary>
/// A collection of the local variables for which a value assigned outside the region may be used inside the region.
/// </summary>
public override ImmutableArray<ISymbol> DataFlowsIn
{
get
{
if (_dataFlowsIn.IsDefault)
{
_succeeded = !_context.Failed;
var result = _context.Failed ? ImmutableArray<ISymbol>.Empty :
Normalize(DataFlowsInWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, UnassignedVariableAddressOfSyntaxes, out _succeeded));
ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsIn, result);
}
return _dataFlowsIn;
}
}
/// <summary>
/// The set of local variables which are definitely assigned a value when a region is
/// entered.
/// </summary>
public override ImmutableArray<ISymbol> DefinitelyAssignedOnEntry
=> ComputeDefinitelyAssignedValues().onEntry;
/// <summary>
/// The set of local variables which are definitely assigned a value when a region is
/// exited.
/// </summary>
public override ImmutableArray<ISymbol> DefinitelyAssignedOnExit
=> ComputeDefinitelyAssignedValues().onExit;
private (ImmutableArray<ISymbol> onEntry, ImmutableArray<ISymbol> onExit) ComputeDefinitelyAssignedValues()
{
// Check for _definitelyAssignedOnExit as that's the last thing we write to. If it's not
// Default, then we'll have written to both variables and can safely read from either of
// them.
if (_definitelyAssignedOnExit.IsDefault)
{
var entryResult = ImmutableArray<ISymbol>.Empty;
var exitResult = ImmutableArray<ISymbol>.Empty;
if (Succeeded)
{
var (entry, exit) = DefinitelyAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion);
entryResult = Normalize(entry);
exitResult = Normalize(exit);
}
ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnEntry, entryResult);
ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnExit, exitResult);
}
return (_definitelyAssignedOnEntry, _definitelyAssignedOnExit);
}
/// <summary>
/// A collection of the local variables for which a value assigned inside the region may be used outside the region.
/// Note that every reachable assignment to a ref or out variable will be included in the results.
/// </summary>
public override ImmutableArray<ISymbol> DataFlowsOut
{
get
{
var discarded = DataFlowsIn; // force DataFlowsIn to be computed
if (_dataFlowsOut.IsDefault)
{
var result = Succeeded
? Normalize(DataFlowsOutWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, _dataFlowsIn))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsOut, result);
}
return _dataFlowsOut;
}
}
/// <summary>
/// A collection of the local variables for which a value is always assigned inside the region.
/// </summary>
public override ImmutableArray<ISymbol> AlwaysAssigned
{
get
{
if (_alwaysAssigned.IsDefault)
{
var result = Succeeded
? Normalize(AlwaysAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _alwaysAssigned, result);
}
return _alwaysAssigned;
}
}
/// <summary>
/// A collection of the local variables that are read inside the region.
/// </summary>
public override ImmutableArray<ISymbol> ReadInside
{
get
{
if (_readInside.IsDefault)
{
AnalyzeReadWrite();
}
return _readInside;
}
}
/// <summary>
/// A collection of local variables that are written inside the region.
/// </summary>
public override ImmutableArray<ISymbol> WrittenInside
{
get
{
if (_writtenInside.IsDefault)
{
AnalyzeReadWrite();
}
return _writtenInside;
}
}
/// <summary>
/// A collection of the local variables that are read outside the region.
/// </summary>
public override ImmutableArray<ISymbol> ReadOutside
{
get
{
if (_readOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _readOutside;
}
}
/// <summary>
/// A collection of local variables that are written outside the region.
/// </summary>
public override ImmutableArray<ISymbol> WrittenOutside
{
get
{
if (_writtenOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _writtenOutside;
}
}
private void AnalyzeReadWrite()
{
IEnumerable<Symbol> readInside, writtenInside, readOutside, writtenOutside, captured, unsafeAddressTaken, capturedInside, capturedOutside;
IEnumerable<MethodSymbol> usedLocalFunctions;
if (Succeeded)
{
ReadWriteWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariableAddressOfSyntaxes,
readInside: out readInside, writtenInside: out writtenInside,
readOutside: out readOutside, writtenOutside: out writtenOutside,
captured: out captured, unsafeAddressTaken: out unsafeAddressTaken,
capturedInside: out capturedInside, capturedOutside: out capturedOutside, usedLocalFunctions: out usedLocalFunctions);
}
else
{
readInside = writtenInside = readOutside = writtenOutside = captured = unsafeAddressTaken = capturedInside = capturedOutside = Enumerable.Empty<Symbol>();
usedLocalFunctions = Enumerable.Empty<MethodSymbol>();
}
ImmutableInterlocked.InterlockedInitialize(ref _readInside, Normalize(readInside));
ImmutableInterlocked.InterlockedInitialize(ref _writtenInside, Normalize(writtenInside));
ImmutableInterlocked.InterlockedInitialize(ref _readOutside, Normalize(readOutside));
ImmutableInterlocked.InterlockedInitialize(ref _writtenOutside, Normalize(writtenOutside));
ImmutableInterlocked.InterlockedInitialize(ref _captured, Normalize(captured));
ImmutableInterlocked.InterlockedInitialize(ref _capturedInside, Normalize(capturedInside));
ImmutableInterlocked.InterlockedInitialize(ref _capturedOutside, Normalize(capturedOutside));
ImmutableInterlocked.InterlockedInitialize(ref _unsafeAddressTaken, Normalize(unsafeAddressTaken));
ImmutableInterlocked.InterlockedInitialize(ref _usedLocalFunctions, Normalize(usedLocalFunctions));
}
/// <summary>
/// A collection of the non-constant local variables and parameters that have been referenced in anonymous functions
/// and therefore must be moved to a field of a frame class.
/// </summary>
public override ImmutableArray<ISymbol> Captured
{
get
{
if (_captured.IsDefault)
{
AnalyzeReadWrite();
}
return _captured;
}
}
public override ImmutableArray<ISymbol> CapturedInside
{
get
{
if (_capturedInside.IsDefault)
{
AnalyzeReadWrite();
}
return _capturedInside;
}
}
public override ImmutableArray<ISymbol> CapturedOutside
{
get
{
if (_capturedOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _capturedOutside;
}
}
/// <summary>
/// A collection of the non-constant local variables and parameters that have had their address (or the address of one
/// of their fields) taken using the '&' operator.
/// </summary>
/// <remarks>
/// If there are any of these in the region, then a method should not be extracted.
/// </remarks>
public override ImmutableArray<ISymbol> UnsafeAddressTaken
{
get
{
if (_unsafeAddressTaken.IsDefault)
{
AnalyzeReadWrite();
}
return _unsafeAddressTaken;
}
}
public override ImmutableArray<IMethodSymbol> UsedLocalFunctions
{
get
{
if (_usedLocalFunctions.IsDefault)
{
AnalyzeReadWrite();
}
return _usedLocalFunctions;
}
}
private HashSet<PrefixUnaryExpressionSyntax> UnassignedVariableAddressOfSyntaxes
{
get
{
if (_unassignedVariableAddressOfSyntaxes == null)
{
var result = Succeeded
? UnassignedAddressTakenVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode)
: new HashSet<PrefixUnaryExpressionSyntax>();
Interlocked.CompareExchange(ref _unassignedVariableAddressOfSyntaxes, result, null);
}
return _unassignedVariableAddressOfSyntaxes;
}
}
/// <summary>
/// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression,
/// a single statement, or a contiguous series of statements within the enclosing block.
/// </summary>
public sealed override bool Succeeded
{
get
{
if (_succeeded == null)
{
var discarded = DataFlowsIn;
}
return _succeeded.Value;
}
}
private static ImmutableArray<ISymbol> Normalize(IEnumerable<Symbol> data)
{
return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).GetPublicSymbols());
}
private static ImmutableArray<IMethodSymbol> Normalize(IEnumerable<MethodSymbol> data)
{
return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).Select(p => p.GetPublicSymbol()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This class implements the region data flow analysis operations. Region data flow analysis
/// provides information how data flows into and out of a region. The analysis is done lazily.
/// When created, it performs no analysis, but simply caches the arguments. Then, the first time
/// one of the analysis results is used it computes that one result and caches it. Each result
/// is computed using a custom algorithm.
/// </summary>
internal class CSharpDataFlowAnalysis : DataFlowAnalysis
{
private readonly RegionAnalysisContext _context;
private ImmutableArray<ISymbol> _variablesDeclared;
private HashSet<Symbol> _unassignedVariables;
private ImmutableArray<ISymbol> _dataFlowsIn;
private ImmutableArray<ISymbol> _dataFlowsOut;
private ImmutableArray<ISymbol> _definitelyAssignedOnEntry;
private ImmutableArray<ISymbol> _definitelyAssignedOnExit;
private ImmutableArray<ISymbol> _alwaysAssigned;
private ImmutableArray<ISymbol> _readInside;
private ImmutableArray<ISymbol> _writtenInside;
private ImmutableArray<ISymbol> _readOutside;
private ImmutableArray<ISymbol> _writtenOutside;
private ImmutableArray<ISymbol> _captured;
private ImmutableArray<IMethodSymbol> _usedLocalFunctions;
private ImmutableArray<ISymbol> _capturedInside;
private ImmutableArray<ISymbol> _capturedOutside;
private ImmutableArray<ISymbol> _unsafeAddressTaken;
private HashSet<PrefixUnaryExpressionSyntax> _unassignedVariableAddressOfSyntaxes;
private bool? _succeeded;
internal CSharpDataFlowAnalysis(RegionAnalysisContext context)
{
_context = context;
}
/// <summary>
/// A collection of the local variables that are declared within the region. Note that the region must be
/// bounded by a method's body or a field's initializer, so method parameter symbols are never included
/// in the result, but lambda parameters might appear in the result.
/// </summary>
public override ImmutableArray<ISymbol> VariablesDeclared
{
// Variables declared in the region is computed by a simple scan.
// ISSUE: are these only variables declared at the top level in the region,
// or are we to include variables declared in deeper scopes within the region?
get
{
if (_variablesDeclared.IsDefault)
{
var result = Succeeded
? Normalize(VariablesDeclaredWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _variablesDeclared, result);
}
return _variablesDeclared;
}
}
private HashSet<Symbol> UnassignedVariables
{
get
{
if (_unassignedVariables == null)
{
var result = Succeeded
? UnassignedVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode)
: new HashSet<Symbol>();
Interlocked.CompareExchange(ref _unassignedVariables, result, null);
}
return _unassignedVariables;
}
}
/// <summary>
/// A collection of the local variables for which a value assigned outside the region may be used inside the region.
/// </summary>
public override ImmutableArray<ISymbol> DataFlowsIn
{
get
{
if (_dataFlowsIn.IsDefault)
{
_succeeded = !_context.Failed;
var result = _context.Failed ? ImmutableArray<ISymbol>.Empty :
Normalize(DataFlowsInWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, UnassignedVariableAddressOfSyntaxes, out _succeeded));
ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsIn, result);
}
return _dataFlowsIn;
}
}
/// <summary>
/// The set of local variables which are definitely assigned a value when a region is
/// entered.
/// </summary>
public override ImmutableArray<ISymbol> DefinitelyAssignedOnEntry
=> ComputeDefinitelyAssignedValues().onEntry;
/// <summary>
/// The set of local variables which are definitely assigned a value when a region is
/// exited.
/// </summary>
public override ImmutableArray<ISymbol> DefinitelyAssignedOnExit
=> ComputeDefinitelyAssignedValues().onExit;
private (ImmutableArray<ISymbol> onEntry, ImmutableArray<ISymbol> onExit) ComputeDefinitelyAssignedValues()
{
// Check for _definitelyAssignedOnExit as that's the last thing we write to. If it's not
// Default, then we'll have written to both variables and can safely read from either of
// them.
if (_definitelyAssignedOnExit.IsDefault)
{
var entryResult = ImmutableArray<ISymbol>.Empty;
var exitResult = ImmutableArray<ISymbol>.Empty;
if (Succeeded)
{
var (entry, exit) = DefinitelyAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion);
entryResult = Normalize(entry);
exitResult = Normalize(exit);
}
ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnEntry, entryResult);
ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnExit, exitResult);
}
return (_definitelyAssignedOnEntry, _definitelyAssignedOnExit);
}
/// <summary>
/// A collection of the local variables for which a value assigned inside the region may be used outside the region.
/// Note that every reachable assignment to a ref or out variable will be included in the results.
/// </summary>
public override ImmutableArray<ISymbol> DataFlowsOut
{
get
{
var discarded = DataFlowsIn; // force DataFlowsIn to be computed
if (_dataFlowsOut.IsDefault)
{
var result = Succeeded
? Normalize(DataFlowsOutWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, _dataFlowsIn))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsOut, result);
}
return _dataFlowsOut;
}
}
/// <summary>
/// A collection of the local variables for which a value is always assigned inside the region.
/// </summary>
public override ImmutableArray<ISymbol> AlwaysAssigned
{
get
{
if (_alwaysAssigned.IsDefault)
{
var result = Succeeded
? Normalize(AlwaysAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion))
: ImmutableArray<ISymbol>.Empty;
ImmutableInterlocked.InterlockedInitialize(ref _alwaysAssigned, result);
}
return _alwaysAssigned;
}
}
/// <summary>
/// A collection of the local variables that are read inside the region.
/// </summary>
public override ImmutableArray<ISymbol> ReadInside
{
get
{
if (_readInside.IsDefault)
{
AnalyzeReadWrite();
}
return _readInside;
}
}
/// <summary>
/// A collection of local variables that are written inside the region.
/// </summary>
public override ImmutableArray<ISymbol> WrittenInside
{
get
{
if (_writtenInside.IsDefault)
{
AnalyzeReadWrite();
}
return _writtenInside;
}
}
/// <summary>
/// A collection of the local variables that are read outside the region.
/// </summary>
public override ImmutableArray<ISymbol> ReadOutside
{
get
{
if (_readOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _readOutside;
}
}
/// <summary>
/// A collection of local variables that are written outside the region.
/// </summary>
public override ImmutableArray<ISymbol> WrittenOutside
{
get
{
if (_writtenOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _writtenOutside;
}
}
private void AnalyzeReadWrite()
{
IEnumerable<Symbol> readInside, writtenInside, readOutside, writtenOutside, captured, unsafeAddressTaken, capturedInside, capturedOutside;
IEnumerable<MethodSymbol> usedLocalFunctions;
if (Succeeded)
{
ReadWriteWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariableAddressOfSyntaxes,
readInside: out readInside, writtenInside: out writtenInside,
readOutside: out readOutside, writtenOutside: out writtenOutside,
captured: out captured, unsafeAddressTaken: out unsafeAddressTaken,
capturedInside: out capturedInside, capturedOutside: out capturedOutside, usedLocalFunctions: out usedLocalFunctions);
}
else
{
readInside = writtenInside = readOutside = writtenOutside = captured = unsafeAddressTaken = capturedInside = capturedOutside = Enumerable.Empty<Symbol>();
usedLocalFunctions = Enumerable.Empty<MethodSymbol>();
}
ImmutableInterlocked.InterlockedInitialize(ref _readInside, Normalize(readInside));
ImmutableInterlocked.InterlockedInitialize(ref _writtenInside, Normalize(writtenInside));
ImmutableInterlocked.InterlockedInitialize(ref _readOutside, Normalize(readOutside));
ImmutableInterlocked.InterlockedInitialize(ref _writtenOutside, Normalize(writtenOutside));
ImmutableInterlocked.InterlockedInitialize(ref _captured, Normalize(captured));
ImmutableInterlocked.InterlockedInitialize(ref _capturedInside, Normalize(capturedInside));
ImmutableInterlocked.InterlockedInitialize(ref _capturedOutside, Normalize(capturedOutside));
ImmutableInterlocked.InterlockedInitialize(ref _unsafeAddressTaken, Normalize(unsafeAddressTaken));
ImmutableInterlocked.InterlockedInitialize(ref _usedLocalFunctions, Normalize(usedLocalFunctions));
}
/// <summary>
/// A collection of the non-constant local variables and parameters that have been referenced in anonymous functions
/// and therefore must be moved to a field of a frame class.
/// </summary>
public override ImmutableArray<ISymbol> Captured
{
get
{
if (_captured.IsDefault)
{
AnalyzeReadWrite();
}
return _captured;
}
}
public override ImmutableArray<ISymbol> CapturedInside
{
get
{
if (_capturedInside.IsDefault)
{
AnalyzeReadWrite();
}
return _capturedInside;
}
}
public override ImmutableArray<ISymbol> CapturedOutside
{
get
{
if (_capturedOutside.IsDefault)
{
AnalyzeReadWrite();
}
return _capturedOutside;
}
}
/// <summary>
/// A collection of the non-constant local variables and parameters that have had their address (or the address of one
/// of their fields) taken using the '&' operator.
/// </summary>
/// <remarks>
/// If there are any of these in the region, then a method should not be extracted.
/// </remarks>
public override ImmutableArray<ISymbol> UnsafeAddressTaken
{
get
{
if (_unsafeAddressTaken.IsDefault)
{
AnalyzeReadWrite();
}
return _unsafeAddressTaken;
}
}
public override ImmutableArray<IMethodSymbol> UsedLocalFunctions
{
get
{
if (_usedLocalFunctions.IsDefault)
{
AnalyzeReadWrite();
}
return _usedLocalFunctions;
}
}
private HashSet<PrefixUnaryExpressionSyntax> UnassignedVariableAddressOfSyntaxes
{
get
{
if (_unassignedVariableAddressOfSyntaxes == null)
{
var result = Succeeded
? UnassignedAddressTakenVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode)
: new HashSet<PrefixUnaryExpressionSyntax>();
Interlocked.CompareExchange(ref _unassignedVariableAddressOfSyntaxes, result, null);
}
return _unassignedVariableAddressOfSyntaxes;
}
}
/// <summary>
/// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression,
/// a single statement, or a contiguous series of statements within the enclosing block.
/// </summary>
public sealed override bool Succeeded
{
get
{
if (_succeeded == null)
{
var discarded = DataFlowsIn;
}
return _succeeded.Value;
}
}
private static ImmutableArray<ISymbol> Normalize(IEnumerable<Symbol> data)
{
return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).GetPublicSymbols());
}
private static ImmutableArray<IMethodSymbol> Normalize(IEnumerable<MethodSymbol> data)
{
return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).Select(p => p.GetPublicSymbol()));
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/VisualBasicTest/Diagnostics/MoveToTopOfFile/MoveToTopOfFileTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.MoveToTopOfFile
Public Class MoveToTopOfFileTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New MoveToTopOfFileCodeFixProvider())
End Function
#Region "Imports Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestTestImportsMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
[|Imports Microsoft|]
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsInsideDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Module Program
[|Imports System|]
Sub Main(args As String())
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsAfterDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]",
"Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsMovedNextToOtherImports() As Task
Dim text = <File>
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]</File>
Dim expected = <File>
Imports Microsoft
Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsMovedAfterOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]</File>
Dim expected = <File>
Option Explicit Off
Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsWithTriviaMovedNextToOtherImports() As Task
Dim text = <File>
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|] 'Comment</File>
Dim expected = <File>
Imports Microsoft
Imports System 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsWithTriviaMovedNextToOtherImportsWithTrivia() As Task
Dim text = <File>
Imports Microsoft 'C1
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|] 'Comment</File>
Dim expected = <File>
Imports Microsoft 'C1
Imports System 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(601222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601222")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOnlyMoveOptions() As Task
Dim text = <File>
Imports Sys = System
Option Infer Off
[|Imports System.IO|]</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
#End Region
#Region "Option Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestTestOptionsMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Option Explicit Off|]
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsInsideDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Module Program
[|Option Explicit Off|]
Sub Main(args As String())
End Sub
End Module",
"Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsAfterDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]",
"Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedNextToOtherOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Text|]</File>
Dim expected = <File>
Option Explicit Off
Option Compare Text
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsWithTriviaMovedNextToOtherOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|] 'Comment</File>
Dim expected = <File>
Option Explicit Off
Option Compare Binary 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsWithTriviaMovedNextToOtherOptionsWithTrivia() As Task
Dim text = <File>
Option Explicit Off'C1
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|] 'Comment</File>
Dim expected = <File>
Option Explicit Off'C1
Option Compare Binary 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerText() As Task
Dim text = <File>
' Copyright
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextThatFollowsEndOfLineTrivia() As Task
Dim text = <File>
' Copyright
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextFollowedByOtherOptions() As Task
Dim text = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Option Compare Binary
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedToTopWithLeadingTriviaButNoBannerText() As Task
Dim text = <File>
#Const A = 5
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>Option Compare Binary
#Const A = 5
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextWithImports() As Task
Dim text = <File>
' Copyright
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>
' Copyright
Option Compare Binary
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
#End Region
#Region "Attribute Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeNoAction1() As Task
Dim text = <File>
[|<Assembly: Reflection.AssemblyCultureAttribute("de")>|]
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeNoAction2() As Task
Dim text = <File>
[|<Assembly: Reflection.AssemblyCultureAttribute("de")>|]
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeAfterDeclaration() As Task
Dim text = <File>
Module Program
Sub Main(args As String())
End Sub
End Module
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeInsideDeclaration() As Task
Dim text = <File>
Module Program
Sub Main(args As String())
End Sub
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
End Module
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributePreserveTrivia() As Task
Dim text = <File>
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Comment
Module Program
Sub Main(args As String())
End Sub
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")> 'Another Comment
End Module
</File>
Dim expected = <File>
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Comment
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Another Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeMovedAfterBannerText() As Task
Dim text = <File>
' Copyright
' License information.
Module Program
Sub Main(args As String())
End Sub
End Module
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
' Copyright
' License information.
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(600949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/600949")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestRemoveAttribute() As Task
Dim text = <File>
Class C
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
End Class
</File>
Dim expected = <File>
Class C
End Class
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag(), index:=1)
End Function
<WorkItem(606857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606857")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestMoveImportBeforeAttribute() As Task
Dim text = <File>
<Assembly:CLSCompliant(True)>
[|Imports System|]</File>
Dim expected = <File>[|Imports System|]
<Assembly:CLSCompliant(True)>
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(606877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606877")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestNewLineWhenMovingFromEOF() As Task
Dim text = <File>Imports System
<Assembly:CLSCompliant(True)>
[|Option Strict On|]</File>
Dim expected = <File>Option Strict On
Imports System
<Assembly:CLSCompliant(True)>
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(606851, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606851")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestDoNotMoveLeadingWhitespace() As Task
Dim text = <File>Imports System
[|Option Strict On|]
</File>
Dim expected = <File>Option Strict On
Imports System
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
#End Region
<WorkItem(632305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632305")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestTestHiddenRegion() As Task
Dim code =
<File>
#ExternalSource ("Goo", 1)
Imports System
#End ExternalSource
Class C
[|Imports Microsoft|]
End Class
</File>
Await TestMissingAsync(code)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.MoveToTopOfFile
Public Class MoveToTopOfFileTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New MoveToTopOfFileCodeFixProvider())
End Function
#Region "Imports Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestTestImportsMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
[|Imports Microsoft|]
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsInsideDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Module Program
[|Imports System|]
Sub Main(args As String())
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsAfterDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]",
"Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsMovedNextToOtherImports() As Task
Dim text = <File>
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]</File>
Dim expected = <File>
Imports Microsoft
Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsMovedAfterOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|]</File>
Dim expected = <File>
Option Explicit Off
Imports System
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsWithTriviaMovedNextToOtherImports() As Task
Dim text = <File>
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|] 'Comment</File>
Dim expected = <File>
Imports Microsoft
Imports System 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestImportsWithTriviaMovedNextToOtherImportsWithTrivia() As Task
Dim text = <File>
Imports Microsoft 'C1
Module Program
Sub Main(args As String())
End Sub
End Module
[|Imports System|] 'Comment</File>
Dim expected = <File>
Imports Microsoft 'C1
Imports System 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(601222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601222")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOnlyMoveOptions() As Task
Dim text = <File>
Imports Sys = System
Option Infer Off
[|Imports System.IO|]</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
#End Region
#Region "Option Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestTestOptionsMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Option Explicit Off|]
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsInsideDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Module Program
[|Option Explicit Off|]
Sub Main(args As String())
End Sub
End Module",
"Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsAfterDeclarations() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]",
"Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedNextToOtherOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Text|]</File>
Dim expected = <File>
Option Explicit Off
Option Compare Text
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsWithTriviaMovedNextToOtherOptions() As Task
Dim text = <File>
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|] 'Comment</File>
Dim expected = <File>
Option Explicit Off
Option Compare Binary 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsWithTriviaMovedNextToOtherOptionsWithTrivia() As Task
Dim text = <File>
Option Explicit Off'C1
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|] 'Comment</File>
Dim expected = <File>
Option Explicit Off'C1
Option Compare Binary 'Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerText() As Task
Dim text = <File>
' Copyright
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextThatFollowsEndOfLineTrivia() As Task
Dim text = <File>
' Copyright
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Explicit Off|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextFollowedByOtherOptions() As Task
Dim text = <File>
' Copyright
Option Explicit Off
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>
' Copyright
Option Explicit Off
Option Compare Binary
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedToTopWithLeadingTriviaButNoBannerText() As Task
Dim text = <File>
#Const A = 5
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>Option Compare Binary
#Const A = 5
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestOptionsMovedAfterBannerTextWithImports() As Task
Dim text = <File>
' Copyright
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
End Sub
End Module
[|Option Compare Binary|]</File>
Dim expected = <File>
' Copyright
Option Compare Binary
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
#End Region
#Region "Attribute Tests"
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeNoAction1() As Task
Dim text = <File>
[|<Assembly: Reflection.AssemblyCultureAttribute("de")>|]
Imports Microsoft
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeNoAction2() As Task
Dim text = <File>
[|<Assembly: Reflection.AssemblyCultureAttribute("de")>|]
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestMissingInRegularAndScriptAsync(text.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeAfterDeclaration() As Task
Dim text = <File>
Module Program
Sub Main(args As String())
End Sub
End Module
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeInsideDeclaration() As Task
Dim text = <File>
Module Program
Sub Main(args As String())
End Sub
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
End Module
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributePreserveTrivia() As Task
Dim text = <File>
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Comment
Module Program
Sub Main(args As String())
End Sub
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")> 'Another Comment
End Module
</File>
Dim expected = <File>
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Comment
<Assembly: Reflection.AssemblyCultureAttribute("de")> 'Another Comment
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(7117, "https://github.com/dotnet/roslyn/issues/7117")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestAttributeMovedAfterBannerText() As Task
Dim text = <File>
' Copyright
' License information.
Module Program
Sub Main(args As String())
End Sub
End Module
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
</File>
Dim expected = <File><Assembly: Reflection.AssemblyCultureAttribute("de")>
' Copyright
' License information.
Module Program
Sub Main(args As String())
End Sub
End Module
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(600949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/600949")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestRemoveAttribute() As Task
Dim text = <File>
Class C
<[|Assembly:|] Reflection.AssemblyCultureAttribute("de")>
End Class
</File>
Dim expected = <File>
Class C
End Class
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag(), index:=1)
End Function
<WorkItem(606857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606857")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestMoveImportBeforeAttribute() As Task
Dim text = <File>
<Assembly:CLSCompliant(True)>
[|Imports System|]</File>
Dim expected = <File>[|Imports System|]
<Assembly:CLSCompliant(True)>
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(606877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606877")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestNewLineWhenMovingFromEOF() As Task
Dim text = <File>Imports System
<Assembly:CLSCompliant(True)>
[|Option Strict On|]</File>
Dim expected = <File>Option Strict On
Imports System
<Assembly:CLSCompliant(True)>
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(606851, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606851")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsMoveToTopOfFile)>
Public Async Function TestDoNotMoveLeadingWhitespace() As Task
Dim text = <File>Imports System
[|Option Strict On|]
</File>
Dim expected = <File>Option Strict On
Imports System
</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
#End Region
<WorkItem(632305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632305")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestTestHiddenRegion() As Task
Dim code =
<File>
#ExternalSource ("Goo", 1)
Imports System
#End ExternalSource
Class C
[|Imports Microsoft|]
End Class
</File>
Await TestMissingAsync(code)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingSpacingPage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
[Guid(Guids.CSharpOptionPageFormattingSpacingIdString)]
internal class FormattingSpacingPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new SpacingViewModel(o, s));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
[Guid(Guids.CSharpOptionPageFormattingSpacingIdString)]
internal class FormattingSpacingPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new SpacingViewModel(o, s));
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class NamedParameterCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(NamedParameterCompletionProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInObjectCreation() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Public Sub New(Optional a As Integer = 42)
End Sub
Private Sub Bar()
Dim b = New Goo($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInBaseConstructor() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Public Sub New(Optional a As Integer = 42)
End Sub
End Class
Class FogBar
Inherits Goo
Public Sub New(b As Integer)
MyBase.New($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeConstructor() As Task
Await VerifyItemIsAbsentAsync(
<Text>
Class Goo
Class TestAttribute
Inherits Attribute
Public Sub New(Optional a As Integer = 42)
End Sub
End Class
<Test($$)> _
Class Goo
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<WorkItem(546190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546190")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeNamedParameter1() As Task
Await VerifyItemExistsAsync(
<Text>
Class SomethingAttribute
Inherits System.Attribute
Public x As Integer
End Class
<Something($$)> ' type x in the parens
Class D
End Class
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeConstructorAfterComma() As Task
Await VerifyItemIsAbsentAsync(
<Text>
Class TestAttribute
Inherits Attribute
Public Sub New(Optional a As Integer = 42, Optional s As String = """")
End Sub
End Class
<Test(s:="""",$$ > _
Class Goo
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpression() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer)
Bar($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpressionAfterComma() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b as String)
Bar(b:="""", $$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInIndexers() As Task
Await VerifyItemExistsAsync(
<Text>
Class Test
Default Public ReadOnly Property Item(i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Module TestModule
Sub Main()
Dim x As Test = New Test()
Dim y As Integer
y = x($$
End Sub
End Module
</Text>.Value, "i", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInDelegates() As Task
Await VerifyItemExistsAsync(
<Text>
Delegate Sub SimpleDelegate(x As Integer)
Module Test
Sub F()
System.Console.WriteLine("Test.F")
End Sub
Sub Main()
Dim d As SimpleDelegate = AddressOf F
d($$
End Sub
End Module
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInDelegateInvokeSyntax() As Task
Await VerifyItemExistsAsync(
<Text>
Delegate Sub SimpleDelegate(x As Integer)
Module Test
Sub F()
System.Console.WriteLine("Test.F")
End Sub
Sub Main()
Dim d As SimpleDelegate = AddressOf F
d.Invoke($$
End Sub
End Module
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterColonEquals() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b As String)
Bar(a:=$$
End Sub
End Class
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInCollectionInitializers() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b As String)
Dim numbers = {1, 2, 3,$$ 4, 5}
End Sub
End Class
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDontFilterYet() As Task
Dim markup =
<Text>
Class Class1
Private Sub Test()
Goo(str:="""", $$)
End Sub
Private Sub Goo(str As String, character As Char)
End Sub
Private Sub Goo(str As String, bool As Boolean)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "bool", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "character", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMethodOverloads() As Task
Dim markup =
<Text>
Class Goo
Private Sub Test()
Dim m As Object = Nothing
Method(obj:=m, $$
End Sub
Private Sub Method(obj As Object, num As Integer, str As String)
End Sub
Private Sub Method(num As Integer, b As Boolean, str As String)
End Sub
Private Sub Method(obj As Object, b As Boolean, str As String)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "str", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "num", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "b", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExistingNamedParamsAreFilteredOut() As Task
Dim markup =
<Text>
Class Goo
Private Sub Test()
Dim m As Object = Nothing
Method(obj:=m, str:="""", $$);
End Sub
Private Sub Method(obj As Object, num As Integer, str As String)
End Sub
Private Sub Method(dbl As Double, str As String)
End Sub
Private Sub Method(num As Integer, b As Boolean, str As String)
End Sub
Private Sub Method(obj As Object, b As Boolean, str As String)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "num", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "b", displayTextSuffix:=":=")
Await VerifyItemIsAbsentAsync(markup, "obj", displayTextSuffix:=":=")
Await VerifyItemIsAbsentAsync(markup, "str", displayTextSuffix:=":=")
End Function
<WorkItem(529370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529370")>
<WpfFact(Skip:="529370"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestKeywordAsEscapedIdentifier() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar([Boolean] As Boolean)
Bar($$
End Sub
End Class
</Text>.Value, "[Boolean]", displayTextSuffix:=":=")
End Function
<WorkItem(546589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546589")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnEquals() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:=
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, "="c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnColon() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, ":"c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnSpace() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:=
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, " "c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer)
Bar(a:=1 ' $$
End Sub
End Class
</Text>.Value)
End Function
<WorkItem(1041260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041260")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestConditionalInvocation() As Task
Await VerifyItemExistsAsync(
<Text>
Imports System
Class Goo
Private Sub Bar(a As Integer)
Dim x as Action(Of Integer) = Nothing
x?($$
End Sub
End Class
</Text>.Value, "obj", displayTextSuffix:=":=")
End Function
<WorkItem(1040247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040247")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExclusivityCheckAfterComma() As Task
Await VerifyAnyItemExistsAsync(
<Text>
Imports System
Class Goo
Private Sub Bar(a As Integer)
Bar(1, 2, $$)
End Sub
End Class
</Text>.Value)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class NamedParameterCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(NamedParameterCompletionProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInObjectCreation() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Public Sub New(Optional a As Integer = 42)
End Sub
Private Sub Bar()
Dim b = New Goo($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInBaseConstructor() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Public Sub New(Optional a As Integer = 42)
End Sub
End Class
Class FogBar
Inherits Goo
Public Sub New(b As Integer)
MyBase.New($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeConstructor() As Task
Await VerifyItemIsAbsentAsync(
<Text>
Class Goo
Class TestAttribute
Inherits Attribute
Public Sub New(Optional a As Integer = 42)
End Sub
End Class
<Test($$)> _
Class Goo
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<WorkItem(546190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546190")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeNamedParameter1() As Task
Await VerifyItemExistsAsync(
<Text>
Class SomethingAttribute
Inherits System.Attribute
Public x As Integer
End Class
<Something($$)> ' type x in the parens
Class D
End Class
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAttributeConstructorAfterComma() As Task
Await VerifyItemIsAbsentAsync(
<Text>
Class TestAttribute
Inherits Attribute
Public Sub New(Optional a As Integer = 42, Optional s As String = """")
End Sub
End Class
<Test(s:="""",$$ > _
Class Goo
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpression() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer)
Bar($$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpressionAfterComma() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b as String)
Bar(b:="""", $$
End Sub
End Class
</Text>.Value, "a", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInIndexers() As Task
Await VerifyItemExistsAsync(
<Text>
Class Test
Default Public ReadOnly Property Item(i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Module TestModule
Sub Main()
Dim x As Test = New Test()
Dim y As Integer
y = x($$
End Sub
End Module
</Text>.Value, "i", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInDelegates() As Task
Await VerifyItemExistsAsync(
<Text>
Delegate Sub SimpleDelegate(x As Integer)
Module Test
Sub F()
System.Console.WriteLine("Test.F")
End Sub
Sub Main()
Dim d As SimpleDelegate = AddressOf F
d($$
End Sub
End Module
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInDelegateInvokeSyntax() As Task
Await VerifyItemExistsAsync(
<Text>
Delegate Sub SimpleDelegate(x As Integer)
Module Test
Sub F()
System.Console.WriteLine("Test.F")
End Sub
Sub Main()
Dim d As SimpleDelegate = AddressOf F
d.Invoke($$
End Sub
End Module
</Text>.Value, "x", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterColonEquals() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b As String)
Bar(a:=$$
End Sub
End Class
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInCollectionInitializers() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer, b As String)
Dim numbers = {1, 2, 3,$$ 4, 5}
End Sub
End Class
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDontFilterYet() As Task
Dim markup =
<Text>
Class Class1
Private Sub Test()
Goo(str:="""", $$)
End Sub
Private Sub Goo(str As String, character As Char)
End Sub
Private Sub Goo(str As String, bool As Boolean)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "bool", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "character", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMethodOverloads() As Task
Dim markup =
<Text>
Class Goo
Private Sub Test()
Dim m As Object = Nothing
Method(obj:=m, $$
End Sub
Private Sub Method(obj As Object, num As Integer, str As String)
End Sub
Private Sub Method(num As Integer, b As Boolean, str As String)
End Sub
Private Sub Method(obj As Object, b As Boolean, str As String)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "str", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "num", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "b", displayTextSuffix:=":=")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExistingNamedParamsAreFilteredOut() As Task
Dim markup =
<Text>
Class Goo
Private Sub Test()
Dim m As Object = Nothing
Method(obj:=m, str:="""", $$);
End Sub
Private Sub Method(obj As Object, num As Integer, str As String)
End Sub
Private Sub Method(dbl As Double, str As String)
End Sub
Private Sub Method(num As Integer, b As Boolean, str As String)
End Sub
Private Sub Method(obj As Object, b As Boolean, str As String)
End Sub
End Class
</Text>.Value
Await VerifyItemExistsAsync(markup, "num", displayTextSuffix:=":=")
Await VerifyItemExistsAsync(markup, "b", displayTextSuffix:=":=")
Await VerifyItemIsAbsentAsync(markup, "obj", displayTextSuffix:=":=")
Await VerifyItemIsAbsentAsync(markup, "str", displayTextSuffix:=":=")
End Function
<WorkItem(529370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529370")>
<WpfFact(Skip:="529370"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestKeywordAsEscapedIdentifier() As Task
Await VerifyItemExistsAsync(
<Text>
Class Goo
Private Sub Bar([Boolean] As Boolean)
Bar($$
End Sub
End Class
</Text>.Value, "[Boolean]", displayTextSuffix:=":=")
End Function
<WorkItem(546589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546589")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnEquals() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:=
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, "="c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnColon() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, ":"c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOnSpace() As Task
Dim text = <Text>
Module Program
Sub Main(args As String())
Main(a$$
End Sub
End Module
</Text>.Value
Dim expected = <Text>
Module Program
Sub Main(args As String())
Main(args:=
End Sub
End Module
</Text>.Value
Await VerifyProviderCommitAsync(text, "args:=", expected, " "c)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Await VerifyNoItemsExistAsync(
<Text>
Class Goo
Private Sub Bar(a As Integer)
Bar(a:=1 ' $$
End Sub
End Class
</Text>.Value)
End Function
<WorkItem(1041260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041260")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestConditionalInvocation() As Task
Await VerifyItemExistsAsync(
<Text>
Imports System
Class Goo
Private Sub Bar(a As Integer)
Dim x as Action(Of Integer) = Nothing
x?($$
End Sub
End Class
</Text>.Value, "obj", displayTextSuffix:=":=")
End Function
<WorkItem(1040247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040247")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExclusivityCheckAfterComma() As Task
Await VerifyAnyItemExistsAsync(
<Text>
Imports System
Class Goo
Private Sub Bar(a As Integer)
Bar(1, 2, $$)
End Sub
End Class
</Text>.Value)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Scripting/Core/Hosting/ObjectFormatter/ObjectFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
public abstract class ObjectFormatter
{
public string FormatObject(object obj) => FormatObject(obj, new PrintOptions());
public abstract string FormatObject(object obj, PrintOptions options);
public abstract string FormatException(Exception e);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
public abstract class ObjectFormatter
{
public string FormatObject(object obj) => FormatObject(obj, new PrintOptions());
public abstract string FormatObject(object obj, PrintOptions options);
public abstract string FormatException(Exception e);
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Symbol/Compilation/IndexedProperties_BindingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
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 Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IndexedProperties_BindingTests : SemanticModelTestBase
{
[ClrOnlyFact]
public void OldGetFormat_IndexedProperties()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = /*<bind>*/a.get_P1/*</bind>*/(1);
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Method, "get_P1");
}
[ClrOnlyFact]
public void IndexedProperties_Complete()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = a./*<bind>*/P1/*</bind>*/[3]++;
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_Incomplete()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = /*<bind>*/a.P1/*</bind>*/[3
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_Set_In_Constructor()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA(){/*<bind>*/P1/*</bind>*/ = 2};
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_LINQ()
{
var reference = GetReference();
var source = @"
using System;
using System.Linq;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var query = from val in arr where val > /*<bind>*/a.P1/*</bind>*/[2] select val;
foreach (var val in query) Console.WriteLine(val);
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
private void IndexedPropertiesBindingChecks(string source, MetadataReference reference, SymbolKind symbolKind, string name)
{
var tree = Parse(source);
var comp = CreateCompilation(tree, new[] { reference });
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var sym = model.GetSymbolInfo(expr);
Assert.Equal(symbolKind, sym.Symbol.Kind);
Assert.Equal(name, sym.Symbol.Name);
var typeInfo = model.GetTypeInfo(expr);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, typeInfo);
var methodGroup = model.GetMemberGroup(expr);
Assert.NotEqual(default, methodGroup);
var indexerGroup = model.GetIndexerGroup(expr);
Assert.NotEqual(default, indexerGroup);
var position = GetPositionForBinding(tree);
// Get the list of LookupNames at the location at the end of the tag
var actual_lookupNames = model.LookupNames(position);
Assert.NotEmpty(actual_lookupNames);
Assert.True(actual_lookupNames.Contains("System"), "LookupNames does not contain System");
Assert.True(actual_lookupNames.Contains("Main"), "LookupNames does not contain Main");
Assert.True(actual_lookupNames.Contains("IA"), "LookupNames does not contain IA");
Assert.True(actual_lookupNames.Contains("A"), "LookupNames does not contain A");
Assert.True(actual_lookupNames.Contains("a"), "LookupNames does not contain a");
// Get the list of LookupSymbols at the location at the end of the tag
var actual_lookupSymbols = model.LookupSymbols(position);
var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString());
Assert.NotEmpty(actual_lookupSymbols_as_string);
Assert.True(actual_lookupSymbols_as_string.Contains("void B.Main(System.String[] args)"), "LookupSymbols does not contain Main");
Assert.True(actual_lookupSymbols_as_string.Contains("System"), "LookupSymbols does not contain System");
Assert.True(actual_lookupSymbols_as_string.Contains("IA"), "LookupSymbols does not contain IA");
Assert.True(actual_lookupSymbols_as_string.Contains("A"), "LookupSymbols does not contain A");
}
private static MetadataReference GetReference()
{
var COMSource = @"
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
<CoClass(GetType(A))>
Public Interface IA
Property P1(Optional index As Integer = 1) As Integer
End Interface
Public Class A
Implements IA
Property P1(Optional index As Integer = 1) As Integer Implements IA.P1
Get
Return 1
End Get
Set
End Set
End Property
End Class
";
var reference = BasicCompilationUtils.CompileToMetadata(COMSource, verify: Verification.Passes);
return reference;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
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 Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IndexedProperties_BindingTests : SemanticModelTestBase
{
[ClrOnlyFact]
public void OldGetFormat_IndexedProperties()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = /*<bind>*/a.get_P1/*</bind>*/(1);
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Method, "get_P1");
}
[ClrOnlyFact]
public void IndexedProperties_Complete()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = a./*<bind>*/P1/*</bind>*/[3]++;
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_Incomplete()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int ret = /*<bind>*/a.P1/*</bind>*/[3
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_Set_In_Constructor()
{
var reference = GetReference();
var source =
@"
using System;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA(){/*<bind>*/P1/*</bind>*/ = 2};
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
[ClrOnlyFact]
public void IndexedProperties_LINQ()
{
var reference = GetReference();
var source = @"
using System;
using System.Linq;
class B
{
static void Main(string[] args)
{
IA a;
a = new IA();
int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var query = from val in arr where val > /*<bind>*/a.P1/*</bind>*/[2] select val;
foreach (var val in query) Console.WriteLine(val);
}
}
";
IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1");
}
private void IndexedPropertiesBindingChecks(string source, MetadataReference reference, SymbolKind symbolKind, string name)
{
var tree = Parse(source);
var comp = CreateCompilation(tree, new[] { reference });
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var sym = model.GetSymbolInfo(expr);
Assert.Equal(symbolKind, sym.Symbol.Kind);
Assert.Equal(name, sym.Symbol.Name);
var typeInfo = model.GetTypeInfo(expr);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, typeInfo);
var methodGroup = model.GetMemberGroup(expr);
Assert.NotEqual(default, methodGroup);
var indexerGroup = model.GetIndexerGroup(expr);
Assert.NotEqual(default, indexerGroup);
var position = GetPositionForBinding(tree);
// Get the list of LookupNames at the location at the end of the tag
var actual_lookupNames = model.LookupNames(position);
Assert.NotEmpty(actual_lookupNames);
Assert.True(actual_lookupNames.Contains("System"), "LookupNames does not contain System");
Assert.True(actual_lookupNames.Contains("Main"), "LookupNames does not contain Main");
Assert.True(actual_lookupNames.Contains("IA"), "LookupNames does not contain IA");
Assert.True(actual_lookupNames.Contains("A"), "LookupNames does not contain A");
Assert.True(actual_lookupNames.Contains("a"), "LookupNames does not contain a");
// Get the list of LookupSymbols at the location at the end of the tag
var actual_lookupSymbols = model.LookupSymbols(position);
var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString());
Assert.NotEmpty(actual_lookupSymbols_as_string);
Assert.True(actual_lookupSymbols_as_string.Contains("void B.Main(System.String[] args)"), "LookupSymbols does not contain Main");
Assert.True(actual_lookupSymbols_as_string.Contains("System"), "LookupSymbols does not contain System");
Assert.True(actual_lookupSymbols_as_string.Contains("IA"), "LookupSymbols does not contain IA");
Assert.True(actual_lookupSymbols_as_string.Contains("A"), "LookupSymbols does not contain A");
}
private static MetadataReference GetReference()
{
var COMSource = @"
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
<CoClass(GetType(A))>
Public Interface IA
Property P1(Optional index As Integer = 1) As Integer
End Interface
Public Class A
Implements IA
Property P1(Optional index As Integer = 1) As Integer Implements IA.P1
Get
Return 1
End Get
Set
End Set
End Property
End Class
";
var reference = BasicCompilationUtils.CompileToMetadata(COMSource, verify: Verification.Passes);
return reference;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal interface IVsTypeScriptVisualStudioProjectFactory
{
[Obsolete("Use CreateAndAddToWorkspaceAsync instead")]
VSTypeScriptVisualStudioProjectWrapper CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid);
ValueTask<VSTypeScriptVisualStudioProjectWrapper> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, 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;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal interface IVsTypeScriptVisualStudioProjectFactory
{
[Obsolete("Use CreateAndAddToWorkspaceAsync instead")]
VSTypeScriptVisualStudioProjectWrapper CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid);
ValueTask<VSTypeScriptVisualStudioProjectWrapper> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.BuilderOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
internal abstract partial class CommonObjectFormatter
{
/// <remarks>
/// Internal for testing.
/// </remarks>
internal struct BuilderOptions
{
public readonly string Indentation;
public readonly string NewLine;
public readonly string Ellipsis;
public readonly int MaximumLineLength;
public readonly int MaximumOutputLength;
public BuilderOptions(string indentation, string newLine, string ellipsis, int maximumLineLength, int maximumOutputLength)
{
Indentation = indentation;
NewLine = newLine;
Ellipsis = ellipsis;
MaximumLineLength = maximumLineLength;
MaximumOutputLength = maximumOutputLength;
}
public BuilderOptions WithMaximumOutputLength(int maximumOutputLength)
{
return new BuilderOptions(
Indentation,
NewLine,
Ellipsis,
MaximumLineLength,
maximumOutputLength);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
internal abstract partial class CommonObjectFormatter
{
/// <remarks>
/// Internal for testing.
/// </remarks>
internal struct BuilderOptions
{
public readonly string Indentation;
public readonly string NewLine;
public readonly string Ellipsis;
public readonly int MaximumLineLength;
public readonly int MaximumOutputLength;
public BuilderOptions(string indentation, string newLine, string ellipsis, int maximumLineLength, int maximumOutputLength)
{
Indentation = indentation;
NewLine = newLine;
Ellipsis = ellipsis;
MaximumLineLength = maximumLineLength;
MaximumOutputLength = maximumOutputLength;
}
public BuilderOptions WithMaximumOutputLength(int maximumOutputLength)
{
return new BuilderOptions(
Indentation,
NewLine,
Ellipsis,
MaximumLineLength,
maximumOutputLength);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/Emit/SynthesizedDelegateValue.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Cci;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct SynthesizedDelegateValue
{
public readonly ITypeDefinition Delegate;
public SynthesizedDelegateValue(ITypeDefinition @delegate)
{
Delegate = @delegate;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Cci;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct SynthesizedDelegateValue
{
public readonly ITypeDefinition Delegate;
public SynthesizedDelegateValue(ITypeDefinition @delegate)
{
Delegate = @delegate;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreation.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.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them
' two times.
Dim objectInitializer = node.InitializerOpt
node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type)
Dim ctor = node.ConstructorOpt
Dim result As BoundExpression = node
If ctor IsNot Nothing Then
Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing
Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing
result = node.Update(ctor,
RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False),
node.DefaultArguments,
Nothing,
ctor.ContainingType)
If Not temporaries.IsDefault Then
result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack)
End If
' If a coclass was instantiated, convert the class to the interface type.
If node.Type.IsInterfaceType() Then
Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType))
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo)
Debug.Assert(Conversions.ConversionExists(conv))
_diagnostics.Add(result, useSiteInfo)
result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing)
Else
Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type))
End If
End If
If objectInitializer IsNot Nothing Then
Return VisitObjectCreationInitializer(objectInitializer, node, result)
End If
Return result
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
' For the NoPIA feature, we need to gather the GUID from the coclass, and
' generate the following:
' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType)
'
' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework),
' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID.
Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)
Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor)
Dim newGuid As BoundExpression
If ctor IsNot Nothing Then
newGuid = factory.[New](ctor, factory.Literal(node.GuidString))
Else
newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True),
factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID))
Dim callGetTypeFromCLSID As BoundExpression
If getTypeFromCLSID IsNot Nothing Then
callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid)
Else
callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance)
Dim rewrittenObjectCreation As BoundExpression
If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo)
_diagnostics.Add(node, useSiteInfo)
rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type)
Else
rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True)
End If
If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then
Return rewrittenObjectCreation
End If
Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation)
End Function
Private Function VisitObjectCreationInitializer(
objectInitializer As BoundObjectInitializerExpressionBase,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then
Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression),
objectCreationExpression, rewrittenObjectCreationExpression)
Else
Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression),
objectCreationExpression, rewrittenObjectCreationExpression)
End If
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()",
' even if T is known to be a value type or reference type. This matches Dev10 VB.
If _inExpressionLambda Then
' NOTE: If we are in expression lambda, we want to keep BoundNewT
' NOTE: node, but we need to rewrite initializers if any.
If node.InitializerOpt IsNot Nothing Then
Return VisitObjectCreationInitializer(node.InitializerOpt, node, node)
Else
Return node
End If
End If
Dim syntax = node.Syntax
Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol)
Dim result As BoundExpression
Dim method As MethodSymbol = Nothing
If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then
Debug.Assert(method IsNot Nothing)
method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter))
result = New BoundCall(syntax,
method,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray(Of BoundExpression).Empty,
constantValueOpt:=Nothing,
isLValue:=False,
suppressObjectClone:=False,
type:=typeParameter)
Else
result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True)
End If
If node.InitializerOpt IsNot Nothing Then
Return VisitObjectCreationInitializer(node.InitializerOpt, result, result)
End If
Return result
End Function
''' <summary>
''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary.
''' E.g. the following code:
''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}}
''' gets rewritten to
''' Dim temp as CollectionType
''' temp = new CollectionType(param1)
''' temp.Add(1)
''' temp.Add(2, 3)
''' temp.Add(4, {5, 6, 7})
''' x = temp
''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression
''' only represents the object creation expression with the initialization.
''' </summary>
''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param>
''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns>
Public Function RewriteCollectionInitializerExpression(
node As BoundCollectionInitializerExpression,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
Debug.Assert(node.PlaceholderOpt IsNot Nothing)
Dim expressionType = node.Type
Dim syntaxNode = node.Syntax
Dim tempLocalSymbol As LocalSymbol
Dim tempLocal As BoundLocal
Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance()
Dim newPlaceholder As BoundWithLValueExpressionPlaceholder
If _inExpressionLambda Then
' A temp is not needed for this case
tempLocalSymbol = Nothing
tempLocal = Nothing
' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to
' keep the double rewrite tracking happy.
newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type)
AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder)
Else
' Create a temp symbol
' Dim temp as CollectionType
' Create assignment for the rewritten object
' creation expression to the temp
' temp = new CollectionType(param1)
tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)
tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)
Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode,
tempLocal,
GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),
suppressObjectClone:=True,
type:=expressionType)
expressions.Add(temporaryAssignment)
newPlaceholder = Nothing
AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal)
End If
Dim initializerCount = node.Initializers.Length
' rewrite the invocation expressions and add them to the expression of the sequence
' temp.Add(...)
For initializerIndex = 0 To initializerCount - 1
' NOTE: if the method Add(...) is omitted we build a local which
' seems to be redundant, this will optimized out later
' by stack scheduler
Dim initializer As BoundExpression = node.Initializers(initializerIndex)
If Not IsOmittedBoundCall(initializer) Then
expressions.Add(VisitExpressionNode(initializer))
End If
Next
RemovePlaceholderReplacement(node.PlaceholderOpt)
If _inExpressionLambda Then
Debug.Assert(tempLocalSymbol Is Nothing)
Debug.Assert(tempLocal Is Nothing)
' NOTE: if inside expression lambda we rewrite the collection initializer
' NOTE: node and attach it back to object creation expression, it will be
' NOTE: rewritten later in ExpressionLambdaRewriter
' Rewrite object creation
Return ReplaceObjectOrCollectionInitializer(
rewrittenObjectCreationExpression,
node.Update(newPlaceholder,
expressions.ToImmutableAndFree(),
node.Type))
Else
Debug.Assert(tempLocalSymbol IsNot Nothing)
Debug.Assert(tempLocal IsNot Nothing)
Return New BoundSequence(syntaxNode,
ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol),
expressions.ToImmutableAndFree(),
tempLocal.MakeRValue(),
expressionType)
End If
End Function
''' <summary>
''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound
''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is
''' stored in the bound object member initializer node itself.
'''
''' E.g. the following code:
''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}
''' gets rewritten to
''' Dim temp as RefTypeName
''' temp = new RefTypeName(param1)
''' temp.FieldName1 = 23
''' temp.FieldName2 = temp.FieldName3
''' temp.FieldName4 = x.FieldName1
''' x = temp
''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression
''' only represents the object creation expression with the initialization.
'''
''' In a case where no temporary is used the following code:
''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}
''' gets rewritten to
''' x = new ValueTypeName(param1)
''' x.FieldName1 = 23
''' x.FieldName2 = x.FieldName3
''' x.FieldName4 = x.FieldName1
''' </summary>
''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param>
''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a
''' bound statement list if no temporary should be used.</returns>
Public Function RewriteObjectInitializerExpression(
node As BoundObjectInitializerExpression,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
Dim targetObjectReference As BoundExpression
Dim expressionType = node.Type
Dim initializerCount = node.Initializers.Length
Dim syntaxNode = node.Syntax
Dim sequenceType As TypeSymbol
Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol)
Dim sequenceValueExpression As BoundExpression
Debug.Assert(node.PlaceholderOpt IsNot Nothing)
' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially
' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to
' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments,
' NOTE: ExpressionLambdaRewriter will get rid of them
' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the
' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself
If node.CreateTemporaryLocalForInitialization Then
' create temporary
' Dim temp as RefTypeName
Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)
sequenceType = expressionType
sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol)
targetObjectReference = If(_inExpressionLambda,
DirectCast(node.PlaceholderOpt, BoundExpression),
New BoundLocal(syntaxNode, tempLocalSymbol, expressionType))
sequenceValueExpression = targetObjectReference.MakeRValue()
AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference)
Else
' Get the receiver for the current initialized variable in case of an "AsNew" declaration
' this is the only case where there might be no temporary needed.
' The replacement for this placeholder was added in VisitAsNewLocalDeclarations.
targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt)
sequenceType = GetSpecialType(SpecialType.System_Void)
sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty
sequenceValueExpression = Nothing
End If
Dim sequenceExpressions(initializerCount) As BoundExpression
' create assignment for object creation expression to temporary or variable declaration
' x = new TypeName(...)
' or
' temp = new TypeName(...)
sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode,
targetObjectReference,
GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),
suppressObjectClone:=True,
type:=expressionType)
' rewrite the assignment expressions and add them to the statement list
' x.FieldName = value expression
' or
' temp.FieldName = value expression
For initializerIndex = 0 To initializerCount - 1
If _inExpressionLambda Then
' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part
' NOTE: will be kept unchanged to make sure we got proper symbol out of it
Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator)
Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing)
sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left,
assignment.LeftOnTheRightOpt,
VisitExpressionNode(assignment.Right),
True,
assignment.Type)
Else
sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex))
End If
Next
If node.CreateTemporaryLocalForInitialization Then
RemovePlaceholderReplacement(node.PlaceholderOpt)
End If
If _inExpressionLambda Then
' when converting object initializer inside expression lambdas we want to keep
' object initializer in object creation expression; we just store visited initializers
' back to the original object initializer and update the original object creation expression
' create new initializers
Dim newInitializers(initializerCount - 1) As BoundExpression
Dim errors As Boolean = False
For index = 0 To initializerCount - 1
newInitializers(index) = sequenceExpressions(index + 1)
Next
' Rewrite object creation
Return ReplaceObjectOrCollectionInitializer(
rewrittenObjectCreationExpression,
node.Update(node.CreateTemporaryLocalForInitialization,
node.PlaceholderOpt,
newInitializers.AsImmutableOrNull(),
node.Type))
End If
Return New BoundSequence(syntaxNode,
sequenceTemporaries,
sequenceExpressions.AsImmutableOrNull,
sequenceValueExpression,
sequenceType)
End Function
Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression
Select Case rewrittenObjectCreationExpression.Kind
Case BoundKind.ObjectCreationExpression
Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression)
Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type)
Case BoundKind.NewT
Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT)
Return newT.Update(rewrittenInitializer, newT.Type)
Case BoundKind.Sequence
' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it
' NOTE: was probably wrapped with sequence which means that this case is not supported
' NOTE: inside expression lambdas.
Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence)
Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression)
Return sequence.Update(sequence.Locals,
sequence.SideEffects,
ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer),
sequence.Type)
Case Else
Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind)
End Select
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them
' two times.
Dim objectInitializer = node.InitializerOpt
node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type)
Dim ctor = node.ConstructorOpt
Dim result As BoundExpression = node
If ctor IsNot Nothing Then
Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing
Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing
result = node.Update(ctor,
RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False),
node.DefaultArguments,
Nothing,
ctor.ContainingType)
If Not temporaries.IsDefault Then
result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack)
End If
' If a coclass was instantiated, convert the class to the interface type.
If node.Type.IsInterfaceType() Then
Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType))
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo)
Debug.Assert(Conversions.ConversionExists(conv))
_diagnostics.Add(result, useSiteInfo)
result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing)
Else
Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type))
End If
End If
If objectInitializer IsNot Nothing Then
Return VisitObjectCreationInitializer(objectInitializer, node, result)
End If
Return result
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
' For the NoPIA feature, we need to gather the GUID from the coclass, and
' generate the following:
' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType)
'
' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework),
' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID.
Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)
Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor)
Dim newGuid As BoundExpression
If ctor IsNot Nothing Then
newGuid = factory.[New](ctor, factory.Literal(node.GuidString))
Else
newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True),
factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID))
Dim callGetTypeFromCLSID As BoundExpression
If getTypeFromCLSID IsNot Nothing Then
callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid)
Else
callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance)
Dim rewrittenObjectCreation As BoundExpression
If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then
Dim useSiteInfo = GetNewCompoundUseSiteInfo()
Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo)
_diagnostics.Add(node, useSiteInfo)
rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type)
Else
rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True)
End If
If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then
Return rewrittenObjectCreation
End If
Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation)
End Function
Private Function VisitObjectCreationInitializer(
objectInitializer As BoundObjectInitializerExpressionBase,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then
Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression),
objectCreationExpression, rewrittenObjectCreationExpression)
Else
Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression),
objectCreationExpression, rewrittenObjectCreationExpression)
End If
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()",
' even if T is known to be a value type or reference type. This matches Dev10 VB.
If _inExpressionLambda Then
' NOTE: If we are in expression lambda, we want to keep BoundNewT
' NOTE: node, but we need to rewrite initializers if any.
If node.InitializerOpt IsNot Nothing Then
Return VisitObjectCreationInitializer(node.InitializerOpt, node, node)
Else
Return node
End If
End If
Dim syntax = node.Syntax
Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol)
Dim result As BoundExpression
Dim method As MethodSymbol = Nothing
If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then
Debug.Assert(method IsNot Nothing)
method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter))
result = New BoundCall(syntax,
method,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray(Of BoundExpression).Empty,
constantValueOpt:=Nothing,
isLValue:=False,
suppressObjectClone:=False,
type:=typeParameter)
Else
result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True)
End If
If node.InitializerOpt IsNot Nothing Then
Return VisitObjectCreationInitializer(node.InitializerOpt, result, result)
End If
Return result
End Function
''' <summary>
''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary.
''' E.g. the following code:
''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}}
''' gets rewritten to
''' Dim temp as CollectionType
''' temp = new CollectionType(param1)
''' temp.Add(1)
''' temp.Add(2, 3)
''' temp.Add(4, {5, 6, 7})
''' x = temp
''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression
''' only represents the object creation expression with the initialization.
''' </summary>
''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param>
''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns>
Public Function RewriteCollectionInitializerExpression(
node As BoundCollectionInitializerExpression,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
Debug.Assert(node.PlaceholderOpt IsNot Nothing)
Dim expressionType = node.Type
Dim syntaxNode = node.Syntax
Dim tempLocalSymbol As LocalSymbol
Dim tempLocal As BoundLocal
Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance()
Dim newPlaceholder As BoundWithLValueExpressionPlaceholder
If _inExpressionLambda Then
' A temp is not needed for this case
tempLocalSymbol = Nothing
tempLocal = Nothing
' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to
' keep the double rewrite tracking happy.
newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type)
AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder)
Else
' Create a temp symbol
' Dim temp as CollectionType
' Create assignment for the rewritten object
' creation expression to the temp
' temp = new CollectionType(param1)
tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)
tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)
Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode,
tempLocal,
GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),
suppressObjectClone:=True,
type:=expressionType)
expressions.Add(temporaryAssignment)
newPlaceholder = Nothing
AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal)
End If
Dim initializerCount = node.Initializers.Length
' rewrite the invocation expressions and add them to the expression of the sequence
' temp.Add(...)
For initializerIndex = 0 To initializerCount - 1
' NOTE: if the method Add(...) is omitted we build a local which
' seems to be redundant, this will optimized out later
' by stack scheduler
Dim initializer As BoundExpression = node.Initializers(initializerIndex)
If Not IsOmittedBoundCall(initializer) Then
expressions.Add(VisitExpressionNode(initializer))
End If
Next
RemovePlaceholderReplacement(node.PlaceholderOpt)
If _inExpressionLambda Then
Debug.Assert(tempLocalSymbol Is Nothing)
Debug.Assert(tempLocal Is Nothing)
' NOTE: if inside expression lambda we rewrite the collection initializer
' NOTE: node and attach it back to object creation expression, it will be
' NOTE: rewritten later in ExpressionLambdaRewriter
' Rewrite object creation
Return ReplaceObjectOrCollectionInitializer(
rewrittenObjectCreationExpression,
node.Update(newPlaceholder,
expressions.ToImmutableAndFree(),
node.Type))
Else
Debug.Assert(tempLocalSymbol IsNot Nothing)
Debug.Assert(tempLocal IsNot Nothing)
Return New BoundSequence(syntaxNode,
ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol),
expressions.ToImmutableAndFree(),
tempLocal.MakeRValue(),
expressionType)
End If
End Function
''' <summary>
''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound
''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is
''' stored in the bound object member initializer node itself.
'''
''' E.g. the following code:
''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}
''' gets rewritten to
''' Dim temp as RefTypeName
''' temp = new RefTypeName(param1)
''' temp.FieldName1 = 23
''' temp.FieldName2 = temp.FieldName3
''' temp.FieldName4 = x.FieldName1
''' x = temp
''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression
''' only represents the object creation expression with the initialization.
'''
''' In a case where no temporary is used the following code:
''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}
''' gets rewritten to
''' x = new ValueTypeName(param1)
''' x.FieldName1 = 23
''' x.FieldName2 = x.FieldName3
''' x.FieldName4 = x.FieldName1
''' </summary>
''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param>
''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a
''' bound statement list if no temporary should be used.</returns>
Public Function RewriteObjectInitializerExpression(
node As BoundObjectInitializerExpression,
objectCreationExpression As BoundExpression,
rewrittenObjectCreationExpression As BoundExpression
) As BoundNode
Dim targetObjectReference As BoundExpression
Dim expressionType = node.Type
Dim initializerCount = node.Initializers.Length
Dim syntaxNode = node.Syntax
Dim sequenceType As TypeSymbol
Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol)
Dim sequenceValueExpression As BoundExpression
Debug.Assert(node.PlaceholderOpt IsNot Nothing)
' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially
' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to
' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments,
' NOTE: ExpressionLambdaRewriter will get rid of them
' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the
' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself
If node.CreateTemporaryLocalForInitialization Then
' create temporary
' Dim temp as RefTypeName
Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)
sequenceType = expressionType
sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol)
targetObjectReference = If(_inExpressionLambda,
DirectCast(node.PlaceholderOpt, BoundExpression),
New BoundLocal(syntaxNode, tempLocalSymbol, expressionType))
sequenceValueExpression = targetObjectReference.MakeRValue()
AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference)
Else
' Get the receiver for the current initialized variable in case of an "AsNew" declaration
' this is the only case where there might be no temporary needed.
' The replacement for this placeholder was added in VisitAsNewLocalDeclarations.
targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt)
sequenceType = GetSpecialType(SpecialType.System_Void)
sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty
sequenceValueExpression = Nothing
End If
Dim sequenceExpressions(initializerCount) As BoundExpression
' create assignment for object creation expression to temporary or variable declaration
' x = new TypeName(...)
' or
' temp = new TypeName(...)
sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode,
targetObjectReference,
GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),
suppressObjectClone:=True,
type:=expressionType)
' rewrite the assignment expressions and add them to the statement list
' x.FieldName = value expression
' or
' temp.FieldName = value expression
For initializerIndex = 0 To initializerCount - 1
If _inExpressionLambda Then
' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part
' NOTE: will be kept unchanged to make sure we got proper symbol out of it
Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator)
Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing)
sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left,
assignment.LeftOnTheRightOpt,
VisitExpressionNode(assignment.Right),
True,
assignment.Type)
Else
sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex))
End If
Next
If node.CreateTemporaryLocalForInitialization Then
RemovePlaceholderReplacement(node.PlaceholderOpt)
End If
If _inExpressionLambda Then
' when converting object initializer inside expression lambdas we want to keep
' object initializer in object creation expression; we just store visited initializers
' back to the original object initializer and update the original object creation expression
' create new initializers
Dim newInitializers(initializerCount - 1) As BoundExpression
Dim errors As Boolean = False
For index = 0 To initializerCount - 1
newInitializers(index) = sequenceExpressions(index + 1)
Next
' Rewrite object creation
Return ReplaceObjectOrCollectionInitializer(
rewrittenObjectCreationExpression,
node.Update(node.CreateTemporaryLocalForInitialization,
node.PlaceholderOpt,
newInitializers.AsImmutableOrNull(),
node.Type))
End If
Return New BoundSequence(syntaxNode,
sequenceTemporaries,
sequenceExpressions.AsImmutableOrNull,
sequenceValueExpression,
sequenceType)
End Function
Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression
Select Case rewrittenObjectCreationExpression.Kind
Case BoundKind.ObjectCreationExpression
Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression)
Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type)
Case BoundKind.NewT
Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT)
Return newT.Update(rewrittenInitializer, newT.Type)
Case BoundKind.Sequence
' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it
' NOTE: was probably wrapped with sequence which means that this case is not supported
' NOTE: inside expression lambdas.
Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence)
Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression)
Return sequence.Update(sequence.Locals,
sequence.SideEffects,
ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer),
sequence.Type)
Case Else
Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind)
End Select
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Symbols/NamespaceOrTypeSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents either a namespace or a type.
''' </summary>
Friend MustInherit Class NamespaceOrTypeSymbol
Inherits Symbol
Implements INamespaceOrTypeSymbol, INamespaceOrTypeSymbolInternal
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Returns true if this symbol is a namespace. If its not a namespace, it must be a type.
''' </summary>
Public ReadOnly Property IsNamespace As Boolean Implements INamespaceOrTypeSymbol.IsNamespace
Get
Return Kind = SymbolKind.Namespace
End Get
End Property
''' <summary>
''' Returns true if this symbols is a type. Equivalent to Not IsNamespace.
''' </summary>
Public ReadOnly Property IsType As Boolean Implements INamespaceOrTypeSymbol.IsType
Get
Return Not IsNamespace
End Get
End Property
''' <summary>
''' Get all the members of this symbol.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetMembers() As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the members of this symbol. The members may not be in a particular order, and the order
''' may not be stable from call-to-call.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
''' returns an empty ImmutableArray. Never returns null.</returns>
Friend Overridable Function GetMembersUnordered() As ImmutableArray(Of Symbol)
'' Default implementation Is to use ordered version. When performance indicates, we specialize to have
'' separate implementation.
Return GetMembers().ConditionallyDeOrder()
End Function
''' <summary>
''' Get all the members of this symbol that have a particular name.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are
''' no members with this name, returns an empty ImmutableArray. The result is deterministic (i.e. the same
''' from call to call and from compilation to compilation). Members of the same kind appear in the result
''' in the same order in which they appeared at their origin (metadata or source).
''' Never returns Nothing.</returns>
Public MustOverride Function GetMembers(name As String) As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the type members of this symbol. The types may not be in a particular order, and the order
''' may not be stable from call-to-call.
''' </summary>
''' <returns>An ImmutableArray containing all the type members of this symbol. If this symbol has no type members,
''' returns an empty ImmutableArray. Never returns null.</returns>
Friend Overridable Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol)
'' Default implementation Is to use ordered version. When performance indicates, we specialize to have
'' separate implementation.
Return GetTypeMembers().ConditionallyDeOrder()
End Function
''' <summary>
''' Get all the members of this symbol that are types.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name, and any arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name.
''' If this symbol has no type members with this name,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name and arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity.
''' If this symbol has no type members with this name and arity,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public Overridable Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
' default implementation does a post-filter. We can override this if its a performance burden, but
' experience is that it won't be.
Return GetTypeMembers(name).WhereAsArray(Function(type, arity_) type.Arity = arity_, arity)
End Function
' Only the compiler can create new instances.
Friend Sub New()
End Sub
''' <summary>
''' Returns true if this symbol was declared as requiring an override; i.e., declared
''' with the "MustOverride" modifier. Never returns true for types.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members and was
''' also restricted from further overriding; i.e., declared with the "NotOverridable"
''' modifier. Never returns true for types.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this member is overridable, has an implementation,
''' and does not override a base class member; i.e., declared with the "Overridable"
''' modifier. Does not return true for members declared as MustOverride or Overrides.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members; i.e., declared
''' with the "Overrides" modifier. Still returns true if the members was declared
''' to override something, but (erroneously) no member to override exists.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' This is a helper method shared between NamedTypeSymbol and NamespaceSymbol.
'''
''' Its purpose is to add names of probable extension methods found in membersByName parameter
''' to nameSet parameter. Method's viability check is delegated to overridable method
''' AddExtensionMethodLookupSymbolsInfoViabilityCheck, which is overridden by RetargetingNamedtypeSymbol
''' and RetargetingNamespaceSymbol in order to perform the check on corresponding RetargetingMethodSymbol.
'''
''' Returns true if there were extension methods among the members,
''' regardless whether their names were added into the set.
''' </summary>
Friend Function AddExtensionMethodLookupSymbolsInfo(
nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
membersByName As IEnumerable(Of KeyValuePair(Of String, ImmutableArray(Of Symbol)))
) As Boolean
Dim haveSeenExtensionMethod As Boolean = False
For Each pair As KeyValuePair(Of String, ImmutableArray(Of Symbol)) In membersByName
' TODO: Should we check whether nameSet already contains pair.Key and
' go to the next pair? If we do that the, haveSeenExtensionMethod == false,
' won't actually mean that there are no extension methods in membersByName.
For Each member As Symbol In pair.Value
If member.Kind = SymbolKind.Method Then
Dim method = DirectCast(member, MethodSymbol)
If method.MayBeReducibleExtensionMethod Then
haveSeenExtensionMethod = True
If AddExtensionMethodLookupSymbolsInfoViabilityCheck(method, options, nameSet, originalBinder) Then
nameSet.AddSymbol(member, member.Name, member.GetArity())
' Move to the next name.
Exit For
End If
End If
End If
Next
Next
Return haveSeenExtensionMethod
End Function
''' <summary>
''' Perform extension method viability check within AppendExtensionMethodNames method above.
''' This method is overridden by RetargetingNamedtypeSymbol and RetargetingNamespaceSymbol in order to
''' perform the check on corresponding RetargetingMethodSymbol.
'''
''' Returns true if the method is viable.
''' </summary>
Friend Overridable Function AddExtensionMethodLookupSymbolsInfoViabilityCheck(
method As MethodSymbol,
options As LookupOptions,
nameSet As LookupSymbolsInfo,
originalBinder As Binder
) As Boolean
Return originalBinder.CanAddLookupSymbolInfo(method, options, nameSet, accessThroughType:=method.ContainingType)
End Function
''' <summary>
''' Finds types or namespaces described by a qualified name.
''' </summary>
''' <param name="qualifiedName">Sequence of simple plain names.</param>
''' <returns> A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities),
''' or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist).
''' </returns>
''' <remarks>
''' "C.D" matches C.D, C(Of T).D, C(Of S,T).D(Of U), etc.
''' </remarks>
Friend Function GetNamespaceOrTypeByQualifiedName(qualifiedName As IEnumerable(Of String)) As IEnumerable(Of NamespaceOrTypeSymbol)
Dim namespaceOrType As NamespaceOrTypeSymbol = Me
Dim symbols As IEnumerable(Of NamespaceOrTypeSymbol) = Nothing
For Each namePart In qualifiedName
If symbols IsNot Nothing Then
namespaceOrType = symbols.OfMinimalArity()
If namespaceOrType Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of NamespaceOrTypeSymbol)()
End If
End If
symbols = namespaceOrType.GetMembers(namePart).OfType(Of NamespaceOrTypeSymbol)()
Next
Return symbols
End Function
#Region "INamespaceOrTypeSymbol"
Private Function INamespaceOrTypeSymbol_GetMembers() As ImmutableArray(Of ISymbol) Implements INamespaceOrTypeSymbol.GetMembers
Return StaticCast(Of ISymbol).From(Me.GetMembers())
End Function
Private Function INamespaceOrTypeSymbol_GetMembers(name As String) As ImmutableArray(Of ISymbol) Implements INamespaceOrTypeSymbol.GetMembers
Return StaticCast(Of ISymbol).From(Me.GetMembers(name))
End Function
Private Function INamespaceOrTypeSymbol_GetTypeMembers() As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers())
End Function
Private Function INamespaceOrTypeSymbol_GetTypeMembers(name As String) As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers(name))
End Function
Public Function INamespaceOrTypeSymbol_GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers(name, arity))
End Function
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents either a namespace or a type.
''' </summary>
Friend MustInherit Class NamespaceOrTypeSymbol
Inherits Symbol
Implements INamespaceOrTypeSymbol, INamespaceOrTypeSymbolInternal
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Returns true if this symbol is a namespace. If its not a namespace, it must be a type.
''' </summary>
Public ReadOnly Property IsNamespace As Boolean Implements INamespaceOrTypeSymbol.IsNamespace
Get
Return Kind = SymbolKind.Namespace
End Get
End Property
''' <summary>
''' Returns true if this symbols is a type. Equivalent to Not IsNamespace.
''' </summary>
Public ReadOnly Property IsType As Boolean Implements INamespaceOrTypeSymbol.IsType
Get
Return Not IsNamespace
End Get
End Property
''' <summary>
''' Get all the members of this symbol.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetMembers() As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the members of this symbol. The members may not be in a particular order, and the order
''' may not be stable from call-to-call.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
''' returns an empty ImmutableArray. Never returns null.</returns>
Friend Overridable Function GetMembersUnordered() As ImmutableArray(Of Symbol)
'' Default implementation Is to use ordered version. When performance indicates, we specialize to have
'' separate implementation.
Return GetMembers().ConditionallyDeOrder()
End Function
''' <summary>
''' Get all the members of this symbol that have a particular name.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are
''' no members with this name, returns an empty ImmutableArray. The result is deterministic (i.e. the same
''' from call to call and from compilation to compilation). Members of the same kind appear in the result
''' in the same order in which they appeared at their origin (metadata or source).
''' Never returns Nothing.</returns>
Public MustOverride Function GetMembers(name As String) As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the type members of this symbol. The types may not be in a particular order, and the order
''' may not be stable from call-to-call.
''' </summary>
''' <returns>An ImmutableArray containing all the type members of this symbol. If this symbol has no type members,
''' returns an empty ImmutableArray. Never returns null.</returns>
Friend Overridable Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol)
'' Default implementation Is to use ordered version. When performance indicates, we specialize to have
'' separate implementation.
Return GetTypeMembers().ConditionallyDeOrder()
End Function
''' <summary>
''' Get all the members of this symbol that are types.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name, and any arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name.
''' If this symbol has no type members with this name,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name and arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity.
''' If this symbol has no type members with this name and arity,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public Overridable Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
' default implementation does a post-filter. We can override this if its a performance burden, but
' experience is that it won't be.
Return GetTypeMembers(name).WhereAsArray(Function(type, arity_) type.Arity = arity_, arity)
End Function
' Only the compiler can create new instances.
Friend Sub New()
End Sub
''' <summary>
''' Returns true if this symbol was declared as requiring an override; i.e., declared
''' with the "MustOverride" modifier. Never returns true for types.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members and was
''' also restricted from further overriding; i.e., declared with the "NotOverridable"
''' modifier. Never returns true for types.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this member is overridable, has an implementation,
''' and does not override a base class member; i.e., declared with the "Overridable"
''' modifier. Does not return true for members declared as MustOverride or Overrides.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members; i.e., declared
''' with the "Overrides" modifier. Still returns true if the members was declared
''' to override something, but (erroneously) no member to override exists.
''' </summary>
''' <returns>
''' Always returns False.
''' </returns>
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' This is a helper method shared between NamedTypeSymbol and NamespaceSymbol.
'''
''' Its purpose is to add names of probable extension methods found in membersByName parameter
''' to nameSet parameter. Method's viability check is delegated to overridable method
''' AddExtensionMethodLookupSymbolsInfoViabilityCheck, which is overridden by RetargetingNamedtypeSymbol
''' and RetargetingNamespaceSymbol in order to perform the check on corresponding RetargetingMethodSymbol.
'''
''' Returns true if there were extension methods among the members,
''' regardless whether their names were added into the set.
''' </summary>
Friend Function AddExtensionMethodLookupSymbolsInfo(
nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
membersByName As IEnumerable(Of KeyValuePair(Of String, ImmutableArray(Of Symbol)))
) As Boolean
Dim haveSeenExtensionMethod As Boolean = False
For Each pair As KeyValuePair(Of String, ImmutableArray(Of Symbol)) In membersByName
' TODO: Should we check whether nameSet already contains pair.Key and
' go to the next pair? If we do that the, haveSeenExtensionMethod == false,
' won't actually mean that there are no extension methods in membersByName.
For Each member As Symbol In pair.Value
If member.Kind = SymbolKind.Method Then
Dim method = DirectCast(member, MethodSymbol)
If method.MayBeReducibleExtensionMethod Then
haveSeenExtensionMethod = True
If AddExtensionMethodLookupSymbolsInfoViabilityCheck(method, options, nameSet, originalBinder) Then
nameSet.AddSymbol(member, member.Name, member.GetArity())
' Move to the next name.
Exit For
End If
End If
End If
Next
Next
Return haveSeenExtensionMethod
End Function
''' <summary>
''' Perform extension method viability check within AppendExtensionMethodNames method above.
''' This method is overridden by RetargetingNamedtypeSymbol and RetargetingNamespaceSymbol in order to
''' perform the check on corresponding RetargetingMethodSymbol.
'''
''' Returns true if the method is viable.
''' </summary>
Friend Overridable Function AddExtensionMethodLookupSymbolsInfoViabilityCheck(
method As MethodSymbol,
options As LookupOptions,
nameSet As LookupSymbolsInfo,
originalBinder As Binder
) As Boolean
Return originalBinder.CanAddLookupSymbolInfo(method, options, nameSet, accessThroughType:=method.ContainingType)
End Function
''' <summary>
''' Finds types or namespaces described by a qualified name.
''' </summary>
''' <param name="qualifiedName">Sequence of simple plain names.</param>
''' <returns> A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities),
''' or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist).
''' </returns>
''' <remarks>
''' "C.D" matches C.D, C(Of T).D, C(Of S,T).D(Of U), etc.
''' </remarks>
Friend Function GetNamespaceOrTypeByQualifiedName(qualifiedName As IEnumerable(Of String)) As IEnumerable(Of NamespaceOrTypeSymbol)
Dim namespaceOrType As NamespaceOrTypeSymbol = Me
Dim symbols As IEnumerable(Of NamespaceOrTypeSymbol) = Nothing
For Each namePart In qualifiedName
If symbols IsNot Nothing Then
namespaceOrType = symbols.OfMinimalArity()
If namespaceOrType Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of NamespaceOrTypeSymbol)()
End If
End If
symbols = namespaceOrType.GetMembers(namePart).OfType(Of NamespaceOrTypeSymbol)()
Next
Return symbols
End Function
#Region "INamespaceOrTypeSymbol"
Private Function INamespaceOrTypeSymbol_GetMembers() As ImmutableArray(Of ISymbol) Implements INamespaceOrTypeSymbol.GetMembers
Return StaticCast(Of ISymbol).From(Me.GetMembers())
End Function
Private Function INamespaceOrTypeSymbol_GetMembers(name As String) As ImmutableArray(Of ISymbol) Implements INamespaceOrTypeSymbol.GetMembers
Return StaticCast(Of ISymbol).From(Me.GetMembers(name))
End Function
Private Function INamespaceOrTypeSymbol_GetTypeMembers() As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers())
End Function
Private Function INamespaceOrTypeSymbol_GetTypeMembers(name As String) As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers(name))
End Function
Public Function INamespaceOrTypeSymbol_GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of INamedTypeSymbol) Implements INamespaceOrTypeSymbol.GetTypeMembers
Return StaticCast(Of INamedTypeSymbol).From(Me.GetTypeMembers(name, arity))
End Function
#End Region
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.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.IO
Imports System.Linq
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class OptionalArgumentsTests
Inherits BasicTestBase
Private ReadOnly _librarySource As XElement =
<compilation>
<file name="library.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System.Reflection
Public Class CBase
Public Overridable Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Public Module Library
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Sub DumpMetadata(a As [Assembly], memberName As String)
If a Is Nothing Then
a = Assembly.GetExecutingAssembly()
End If
Dim t As Type
For Each t In a.GetExportedTypes()
' For each type, show its members & their custom attributes.
For Each mi In t.GetMembers()
If memberName Is Nothing OrElse mi.Name = memberName Then
' If the member is a method, display information about its parameters.
If mi.MemberType = MemberTypes.Method Then
Console.WriteLine("Member: {0}", mi.Name)
For Each pi In CType(mi, MethodInfo).GetParameters()
Dim defval As Object = pi.DefaultValue
If pi.DefaultValue Is Nothing Then
defval = "No Default"
Else
Dim vType = pi.DefaultValue.GetType()
If vType Is GetType(DateTime) Then
defval = DirectCast(pi.DefaultValue, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul)
ElseIf vType Is GetType(Single) Then
defval = DirectCast(pi.DefaultValue, Single).ToString(cul)
ElseIf vType Is GetType(Double) Then
defval = DirectCast(pi.DefaultValue, Double).ToString(cul)
ElseIf vType Is GetType(Decimal) Then
defval = DirectCast(pi.DefaultValue, Decimal).ToString(cul)
End If
End If
Console.WriteLine("Parameter: Type={0}, Name={1}, Optional={2}, DefaultValue={3}", pi.ParameterType, pi.Name, pi.IsOptional, defval)
DisplayAttributes(pi.GetCustomAttributes(False))
Next
If memberName IsNot Nothing Then
Exit For
End If
End If
End If
Next
Next
End Sub
Sub DisplayAttributes(attrs() As Object)
If attrs.Length = 0 Then Return
' Display the custom attributes applied to this member.
Dim o As Object
For Each o In attrs
Dim dateTimeAttribute = TryCast(o, DateTimeConstantAttribute)
Dim decimalAttribute = TryCast(o, DecimalConstantAttribute)
If dateTimeAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), DirectCast(dateTimeAttribute.Value, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul))
ElseIf decimalAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), decimalAttribute.Value.ToString(cul))
End If
Next
End Sub
' 634631328000000000 = #1/26/2012#.Ticks. Optional pseudo attribute is missing.
Sub DateTimeUsingConstantAttribute(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
Sub DateTimeUsingOptionalAttribute(<[Optional]()> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DateTimeUsingOptionalAndConstantAttributes(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DecimalUsingOptionalAndConstantAttributes(<[Optional]()> <DecimalConstant(2, 0, 0, 0, 99999)> i As Decimal)
Console.WriteLine(i.ToString(cul))
End Sub
Sub IntegerUsingOptionalAttribute(<[Optional]()> i As Integer)
Console.WriteLine(i)
End Sub
Sub StringUsingOptionalAttribute(<[Optional]()> i As String)
Console.WriteLine(i IsNot Nothing)
End Sub
' DateTime constant with a string parameter.
' Valid to call with strict off. Error with strict on
Sub StringWithOptionalDateTimeValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As String)
Console.WriteLine(i)
End Sub
' DateTime constant with a integer parameter.
' Always an error
Sub IntegerWithDateTimeOptionalValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As Integer)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Property with optional parameter
Property PropertyIntegerOptionalDouble(i As Integer, Optional j As Double = 100)
Get
Return j
End Get
Set(ByVal value)
End Set
End Property
Public Enum Animal
Dog
Cat
Fish
End Enum
Sub TestWithMultipleOptionalEnumValues(Optional e1 As Animal = Animal.Dog, Optional e2 As Animal = Animal.Cat)
End Sub
End Module
]]></file>
</compilation>
Private ReadOnly _classLibrary As MetadataReference = CreateHelperLibrary(_librarySource.Value)
Public Function CreateHelperLibrary(source As String) As MetadataReference
Dim libraryCompilation = VisualBasicCompilation.Create("library",
{VisualBasicSyntaxTree.ParseText(source)},
{MsvbRef, MscorlibRef, SystemCoreRef},
TestOptions.ReleaseDll)
Return MetadataReference.CreateFromImage(libraryCompilation.EmitToArray())
End Function
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalInteger()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Integer = 1)
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=1
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestIntegerOptionalAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(<[Optional]()> i As Integer)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=System.Reflection.Missing
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalString()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As String = "hello world")
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = hello world
Member: OptionalArg
Parameter: Type=System.String, Name=i, Optional=True, DefaultValue=hello world
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalDateTime()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As DateTime = #1/26/2012#)
Console.WriteLine("i = {0}", i.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1/26/2012 12:00:00 AM
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalDecimal()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Decimal = 999.99D)
Console.WriteLine("i = {0}", i.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 999.99
Member: OptionalArg
Parameter: Type=System.Decimal, Name=i, Optional=True, DefaultValue=999.99
Attribute: System.Runtime.CompilerServices.DecimalConstantAttribute(999.99)
]]>)
End Sub
<WorkItem(543530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543530")>
<Fact()>
Public Sub OptionalForConstructorofAttribute()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class Base1
Inherits Attribute
Sub New(Optional x As System.Type = Nothing)
Me.Result = If(x Is Nothing, "Nothing", x.ToString())
End Sub
Public Result As String
End Class
Class C1
<Base1()>
Shared Sub A()
End Sub
<Base1(Nothing)>
Shared Sub B(name As String)
Dim m = GetType(C1).GetMethod(name)
Console.Write(DirectCast(m.GetCustomAttributes(GetType(Base1), False)(0), Base1).Result)
Console.Write(";")
End Sub
<Base1(GetType(C1))>
Shared Sub Main()
B("A")
B("B")
B("Main")
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:="Nothing;Nothing;C1;")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestDateTimeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=False, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestDateTimeOptionalAttributeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeMissingOptionalFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
DateTimeUsingConstantAttribute() ' This should error. Optional pseudo attribute is missing from metadata.
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "DateTimeUsingConstantAttribute").WithArguments("i", "Public Sub DateTimeUsingConstantAttribute(i As Date)"))
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAndConstantAttributes() ' This should work both optional and datetimeconstant attributes are in metadata.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
1/26/2012 12:00:00 AM
]]>)
End Sub
<Fact()>
Public Sub TestDecimalFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DecimalUsingOptionalAndConstantAttributes()
' Dev10 does not pick up the DecimalConstantAttribute because it uses the
' Integer constructor instead of the UInteger constructor.
' Roslyn honours both constructors.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
999.99
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataOptionalAttributeOnly()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAttribute() ' Metadata only has the optional attribute.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
1/1/0001 12:00:00 AM
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalWithNothing()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C1
End Class
Structure S1
dim i as integer
End Structure
Module Module1
Sub s1(optional s as byte = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s2(optional s as boolean = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s3(optional s as integer = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s4(optional s as long = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s5(optional s as double = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s6(optional s as datetime = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s7(optional s as decimal = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s8(optional s as string = nothing)
Console.WriteLine(s = nothing)
end Sub
Sub s9(optional s as C1 = nothing)
Console.WriteLine(s is nothing)
end Sub
Sub s10(optional s as S1 = nothing)
dim t as S1 = nothing
Console.WriteLine(s.Equals(t))
end Sub
Sub Main()
s1()
s2()
s3()
s4()
s5()
s6()
s7()
s8()
s9()
s10()
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
True
True
True
True
True
True
True
True
True
True
]]>)
End Sub
<Fact()>
Public Sub TestBadDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub s(optional i as integer = p) ' p is undefined and will be a BadExpression.
End Sub
Sub Main()
s()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "p").WithArguments("p"))
End Sub
<Fact()>
Public Sub ParamArrayAndAttribute()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
Sub M1(ParamArray o As Object())
Sub M2(<[ParamArray]()> o As Object())
Sub M3(<[ParamArray]()> ParamArray o As Object())
Property P1(ParamArray o As Object())
Property P2(<[ParamArray]()> o As Object())
Property P3(<[ParamArray]()> ParamArray o As Object())
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("I")
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P3").Parameters(0)))
End Sub)
End Sub
Private Shared Function CountParamArrayAttributes(parameter As ParameterSymbol) As Integer
Dim [module] = DirectCast(parameter.ContainingModule, PEModuleSymbol)
Dim attributes = [module].GetCustomAttributesForToken(DirectCast(parameter, PEParameterSymbol).Handle)
Return attributes.Where(Function(a) a.AttributeClass.Name = "ParamArrayAttribute").Count()
End Function
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesMetadata()
Dim ilSource = <![CDATA[
.assembly extern System {}
.class public C
{
.method public static object F0([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F1([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static object F2([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F3([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
.method public static int32 F4([opt] int32 i)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 01 00 00 00 00 00 ) // [DefaultParameterValue(1)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 02 00 00 00 00 00 ) // [DefaultParameterValue(2)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 03 00 00 00 00 00 ) // [DefaultParameterValue(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.DateTime F5([opt] valuetype [mscorlib]System.DateTime d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 01 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 02 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.Decimal F6([opt] valuetype [mscorlib]System.Decimal d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
}
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F0())
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5().Ticks)
Report(C.F6())
End Sub
Shared Sub Report(o As Object)
Dim value As Object = If (TypeOf o is Date, DirectCast(o, Date).ToString("yyyy-MM-dd HH:mm:ss"), o)
System.Console.WriteLine("{0}: {1}", o.GetType(), value)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, expectedOutput:=<![CDATA[
System.Reflection.Missing: System.Reflection.Missing
System.DateTime: 0001-01-01 00:00:00
System.DateTime: 0001-01-01 00:00:00
System.DateTime: 0001-01-01 00:00:00
System.Int32: 0
System.Int64: 3
System.Decimal: 3
]]>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues()
Dim source1 =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Function F1(Optional o As Integer = 1)
Return o
End Function
Public Shared Function F2(<[Optional](), DefaultParameterValue(2)> o As Integer)
Return o
End Function
Public Shared Function F3(<DefaultParameterValue(3)> Optional o As Integer = 3)
Return o
End Function
Public Shared Function F4(Optional o As Decimal = 4)
Return o
End Function
Public Shared Function F5(<[Optional](), DecimalConstant(0, 0, 0, 0, 5)> o As Decimal)
Return o
End Function
Public Shared Function F6(<DecimalConstant(0, 0, 0, 0, 6)> Optional o As Decimal = 6)
Return o
End Function
Public Shared Function F7(Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Function F8(<[Optional](), DateTimeConstant(635102208000000000)> o As DateTime)
Return o
End Function
Public Shared Function F9(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Property P(<DecimalConstant(0, 0, 0, 0, 10)> Optional o As Decimal = 10)
Get
Return o
End Get
Set
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(source1)
comp1.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp1, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), Nothing, 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DefaultParameterValueAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DefaultParameterValueAttribute", 3, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F4").Parameters(0), "DecimalConstantAttribute", 4UI, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F5").Parameters(0), "DecimalConstantAttribute", 5, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F6").Parameters(0), "DecimalConstantAttribute", 6, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F7").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F8").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F9").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of PropertySymbol)("P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("get_P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("set_P").Parameters(0), "DecimalConstantAttribute", 10, False)
End Sub)
Dim source2 =
<compilation>
<file name="a.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5())
Report(C.F6())
Report(C.F7().Ticks)
Report(C.F8().Ticks)
Report(C.F9().Ticks)
Report(C.P)
End Sub
Shared Sub Report(o As Object)
System.Console.WriteLine(o)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp2a = CreateCompilationWithMscorlib40AndVBRuntime(
source2,
additionalRefs:={New VisualBasicCompilationReference(comp1)},
options:=TestOptions.DebugExe)
comp2a.AssertTheseDiagnostics(
<errors>
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F2(o As Integer) As Object'.
Report(C.F2())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F5(o As Decimal) As Object'.
Report(C.F5())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F8(o As Date) As Object'.
Report(C.F8().Ticks)
~~
</errors>)
Dim comp2b = CreateCompilationWithMscorlib40AndVBRuntime(
source2,
additionalRefs:={MetadataReference.CreateFromImage(comp1.EmitToArray())},
options:=TestOptions.DebugExe)
comp2b.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp2b, expectedOutput:=
<![CDATA[
1
0
3
4
5
6
635102208000000000
635102208000000000
635102208000000000
10
]]>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 1)
End Sub
Private Sub F2(Optional o As Decimal = 2)
End Sub
Private Partial Sub F3(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 1)
End Sub
Private Partial Sub F2(<DecimalConstant(0, 0, 0, 0, 2)> Optional o As Decimal = 2)
End Sub
Private Sub F3(Optional o As DateTime = #7/24/2013#)
End Sub
End Class
]]>
</file>
</compilation>,
options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(comp, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), "DefaultParameterValueAttribute", 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DecimalConstantAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
End Sub)
End Sub
Private Shared Sub VerifyDefaultValueAttribute(parameter As ParameterSymbol, expectedAttributeName As String, expectedDefault As Object, hasDefault As Boolean)
Dim attributes = DirectCast(parameter.ContainingModule, PEModuleSymbol).
GetCustomAttributesForToken(DirectCast(parameter, PEParameterSymbol).Handle).
Where(Function(attr) attr.AttributeClass.Name = expectedAttributeName).
ToArray()
If expectedAttributeName Is Nothing Then
Assert.Equal(attributes.Length, 0)
Else
Assert.Equal(attributes.Length, 1)
Dim attribute = DirectCast(attributes(0), VisualBasicAttributeData)
Dim argument = attribute.ConstructorArguments.Last()
Assert.Equal(expectedDefault, argument.Value)
End If
If hasDefault Then
Assert.Equal(expectedDefault, parameter.ExplicitDefaultValue)
End If
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
<DefaultParameterValue(3)> Optional b As Decimal = 4,
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Interface
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(3)> Optional b As Decimal = 4,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
End Sub
Private Partial Sub F9(<DefaultParameterValue(0)> o As Integer)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 2)
End Sub
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Sub
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Partial Sub F1(Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
''' <summary>
''' Should not report differences if either value is bad.
''' </summary>
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_BadValue()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
Sub M3(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'C' is not defined.
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~
BC37226: The parameter has multiple distinct default values.
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'C' is not defined.
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
~
BC37226: The parameter has multiple distinct default values.
Sub M3(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub TestOptionalAttributeWithoutDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
IntegerUsingOptionalAttribute()
StringUsingOptionalAttribute()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
0
False
]]>)
End Sub
<WorkItem(543076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543076")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestPropertyIntegerOptionalDouble()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DumpMetadata(nothing, "get_PropertyIntegerOptionalDouble")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: get_PropertyIntegerOptionalDouble
Parameter: Type=System.Int32, Name=i, Optional=False, DefaultValue=
Parameter: Type=System.Double, Name=j, Optional=True, DefaultValue=100
]]>)
End Sub
<WorkItem(543093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543093")>
<Fact()>
Public Sub TestIntegerWithDateTimeOptionalValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
IntegerWithDateTimeOptionalValue()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "IntegerWithDateTimeOptionalValue()").WithArguments("Date", "Integer"))
End Sub
<WorkItem(543093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543093")>
<ConditionalFact(GetType(NoIOperationValidation))> ' Disabling for IOperation run due to https://github.com/dotnet/roslyn/issues/26895
Public Sub TestStringWithOptionalDateTimeValue()
' Error when option strict is on
' No error when option strict is off
Dim expectedDiagnostics = {
Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "StringWithOptionalDateTimeValue()").WithArguments("Date", "String"),
Nothing}
Dim i = 0
For Each o In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= o %>
Module Module1
Sub Main()
StringWithOptionalDateTimeValue()
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
Dim diag = expectedDiagnostics(i)
If diag IsNot Nothing Then
comp.VerifyDiagnostics(diag)
Else
comp.VerifyDiagnostics()
End If
i += 1
Next
End Sub
<WorkItem(543139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543139")>
<Fact()>
Public Sub TestOverrideOptionalArgumentFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class CDerived
Inherits CBase
Public Overrides Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
]]>)
End Sub
<WorkItem(543227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543227")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestMultipleEnumDefaultValuesFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
TestWithMultipleOptionalEnumValues()
DumpMetadata(nothing, "TestWithMultipleOptionalEnumValues")
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: TestWithMultipleOptionalEnumValues
Parameter: Type=Library+Animal, Name=e1, Optional=True, DefaultValue=Dog
Parameter: Type=Library+Animal, Name=e2, Optional=True, DefaultValue=Cat
]]>)
End Sub
' Test with omitted argument syntax and an error
' Test without omitted argument syntax and an error
<Fact()>
Public Sub TestExplicitConstantAttributesOnFields_Error()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DecimalConstant(0, 0, 0, 0, 0)> Public F0 As DateTime
<DateTimeConstant(0)> Public F1 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
<DateTimeConstant(0)> Public Const F10 As Integer = 0
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F10 As Integer = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub TestExplicitConstantAttributesOnFields_Valid()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DecimalConstantAttribute(0, 128, 0, 0, 7)> Public Const F1 as Decimal = -7
<DateTimeConstantAttribute(634925952000000000)> Public Const F2 as Date = #1/1/2013#
End Class
]]>
</file>
</compilation>)
CompileAndVerify(comp, symbolValidator:=Sub([module] As ModuleSymbol)
Dim peModule = DirectCast([module], PEModuleSymbol)
Dim type = peModule.GlobalNamespace.GetTypeMember("C")
Dim f1 = DirectCast(type.GetMember("F1"), PEFieldSymbol)
Assert.Equal(1, peModule.GetCustomAttributesForToken(f1.Handle).Length)
Dim f2 = DirectCast(type.GetMember("F2"), PEFieldSymbol)
Assert.Equal(1, peModule.GetCustomAttributesForToken(f2.Handle).Length)
End Sub)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.IO
Imports System.Linq
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class OptionalArgumentsTests
Inherits BasicTestBase
Private ReadOnly _librarySource As XElement =
<compilation>
<file name="library.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System.Reflection
Public Class CBase
Public Overridable Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Public Module Library
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Sub DumpMetadata(a As [Assembly], memberName As String)
If a Is Nothing Then
a = Assembly.GetExecutingAssembly()
End If
Dim t As Type
For Each t In a.GetExportedTypes()
' For each type, show its members & their custom attributes.
For Each mi In t.GetMembers()
If memberName Is Nothing OrElse mi.Name = memberName Then
' If the member is a method, display information about its parameters.
If mi.MemberType = MemberTypes.Method Then
Console.WriteLine("Member: {0}", mi.Name)
For Each pi In CType(mi, MethodInfo).GetParameters()
Dim defval As Object = pi.DefaultValue
If pi.DefaultValue Is Nothing Then
defval = "No Default"
Else
Dim vType = pi.DefaultValue.GetType()
If vType Is GetType(DateTime) Then
defval = DirectCast(pi.DefaultValue, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul)
ElseIf vType Is GetType(Single) Then
defval = DirectCast(pi.DefaultValue, Single).ToString(cul)
ElseIf vType Is GetType(Double) Then
defval = DirectCast(pi.DefaultValue, Double).ToString(cul)
ElseIf vType Is GetType(Decimal) Then
defval = DirectCast(pi.DefaultValue, Decimal).ToString(cul)
End If
End If
Console.WriteLine("Parameter: Type={0}, Name={1}, Optional={2}, DefaultValue={3}", pi.ParameterType, pi.Name, pi.IsOptional, defval)
DisplayAttributes(pi.GetCustomAttributes(False))
Next
If memberName IsNot Nothing Then
Exit For
End If
End If
End If
Next
Next
End Sub
Sub DisplayAttributes(attrs() As Object)
If attrs.Length = 0 Then Return
' Display the custom attributes applied to this member.
Dim o As Object
For Each o In attrs
Dim dateTimeAttribute = TryCast(o, DateTimeConstantAttribute)
Dim decimalAttribute = TryCast(o, DecimalConstantAttribute)
If dateTimeAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), DirectCast(dateTimeAttribute.Value, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul))
ElseIf decimalAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), decimalAttribute.Value.ToString(cul))
End If
Next
End Sub
' 634631328000000000 = #1/26/2012#.Ticks. Optional pseudo attribute is missing.
Sub DateTimeUsingConstantAttribute(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
Sub DateTimeUsingOptionalAttribute(<[Optional]()> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DateTimeUsingOptionalAndConstantAttributes(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DecimalUsingOptionalAndConstantAttributes(<[Optional]()> <DecimalConstant(2, 0, 0, 0, 99999)> i As Decimal)
Console.WriteLine(i.ToString(cul))
End Sub
Sub IntegerUsingOptionalAttribute(<[Optional]()> i As Integer)
Console.WriteLine(i)
End Sub
Sub StringUsingOptionalAttribute(<[Optional]()> i As String)
Console.WriteLine(i IsNot Nothing)
End Sub
' DateTime constant with a string parameter.
' Valid to call with strict off. Error with strict on
Sub StringWithOptionalDateTimeValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As String)
Console.WriteLine(i)
End Sub
' DateTime constant with a integer parameter.
' Always an error
Sub IntegerWithDateTimeOptionalValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As Integer)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Property with optional parameter
Property PropertyIntegerOptionalDouble(i As Integer, Optional j As Double = 100)
Get
Return j
End Get
Set(ByVal value)
End Set
End Property
Public Enum Animal
Dog
Cat
Fish
End Enum
Sub TestWithMultipleOptionalEnumValues(Optional e1 As Animal = Animal.Dog, Optional e2 As Animal = Animal.Cat)
End Sub
End Module
]]></file>
</compilation>
Private ReadOnly _classLibrary As MetadataReference = CreateHelperLibrary(_librarySource.Value)
Public Function CreateHelperLibrary(source As String) As MetadataReference
Dim libraryCompilation = VisualBasicCompilation.Create("library",
{VisualBasicSyntaxTree.ParseText(source)},
{MsvbRef, MscorlibRef, SystemCoreRef},
TestOptions.ReleaseDll)
Return MetadataReference.CreateFromImage(libraryCompilation.EmitToArray())
End Function
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalInteger()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Integer = 1)
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=1
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestIntegerOptionalAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(<[Optional]()> i As Integer)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=System.Reflection.Missing
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalString()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As String = "hello world")
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = hello world
Member: OptionalArg
Parameter: Type=System.String, Name=i, Optional=True, DefaultValue=hello world
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalDateTime()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As DateTime = #1/26/2012#)
Console.WriteLine("i = {0}", i.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1/26/2012 12:00:00 AM
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalDecimal()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Decimal = 999.99D)
Console.WriteLine("i = {0}", i.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
i = 999.99
Member: OptionalArg
Parameter: Type=System.Decimal, Name=i, Optional=True, DefaultValue=999.99
Attribute: System.Runtime.CompilerServices.DecimalConstantAttribute(999.99)
]]>)
End Sub
<WorkItem(543530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543530")>
<Fact()>
Public Sub OptionalForConstructorofAttribute()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class Base1
Inherits Attribute
Sub New(Optional x As System.Type = Nothing)
Me.Result = If(x Is Nothing, "Nothing", x.ToString())
End Sub
Public Result As String
End Class
Class C1
<Base1()>
Shared Sub A()
End Sub
<Base1(Nothing)>
Shared Sub B(name As String)
Dim m = GetType(C1).GetMethod(name)
Console.Write(DirectCast(m.GetCustomAttributes(GetType(Base1), False)(0), Base1).Result)
Console.Write(";")
End Sub
<Base1(GetType(C1))>
Shared Sub Main()
B("A")
B("B")
B("Main")
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:="Nothing;Nothing;C1;")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestDateTimeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=False, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestDateTimeOptionalAttributeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeMissingOptionalFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
DateTimeUsingConstantAttribute() ' This should error. Optional pseudo attribute is missing from metadata.
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "DateTimeUsingConstantAttribute").WithArguments("i", "Public Sub DateTimeUsingConstantAttribute(i As Date)"))
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAndConstantAttributes() ' This should work both optional and datetimeconstant attributes are in metadata.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
1/26/2012 12:00:00 AM
]]>)
End Sub
<Fact()>
Public Sub TestDecimalFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DecimalUsingOptionalAndConstantAttributes()
' Dev10 does not pick up the DecimalConstantAttribute because it uses the
' Integer constructor instead of the UInteger constructor.
' Roslyn honours both constructors.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
999.99
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataOptionalAttributeOnly()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAttribute() ' Metadata only has the optional attribute.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
1/1/0001 12:00:00 AM
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestOptionalWithNothing()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C1
End Class
Structure S1
dim i as integer
End Structure
Module Module1
Sub s1(optional s as byte = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s2(optional s as boolean = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s3(optional s as integer = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s4(optional s as long = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s5(optional s as double = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s6(optional s as datetime = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s7(optional s as decimal = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s8(optional s as string = nothing)
Console.WriteLine(s = nothing)
end Sub
Sub s9(optional s as C1 = nothing)
Console.WriteLine(s is nothing)
end Sub
Sub s10(optional s as S1 = nothing)
dim t as S1 = nothing
Console.WriteLine(s.Equals(t))
end Sub
Sub Main()
s1()
s2()
s3()
s4()
s5()
s6()
s7()
s8()
s9()
s10()
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
True
True
True
True
True
True
True
True
True
True
]]>)
End Sub
<Fact()>
Public Sub TestBadDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub s(optional i as integer = p) ' p is undefined and will be a BadExpression.
End Sub
Sub Main()
s()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "p").WithArguments("p"))
End Sub
<Fact()>
Public Sub ParamArrayAndAttribute()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
Sub M1(ParamArray o As Object())
Sub M2(<[ParamArray]()> o As Object())
Sub M3(<[ParamArray]()> ParamArray o As Object())
Property P1(ParamArray o As Object())
Property P2(<[ParamArray]()> o As Object())
Property P3(<[ParamArray]()> ParamArray o As Object())
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("I")
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P3").Parameters(0)))
End Sub)
End Sub
Private Shared Function CountParamArrayAttributes(parameter As ParameterSymbol) As Integer
Dim [module] = DirectCast(parameter.ContainingModule, PEModuleSymbol)
Dim attributes = [module].GetCustomAttributesForToken(DirectCast(parameter, PEParameterSymbol).Handle)
Return attributes.Where(Function(a) a.AttributeClass.Name = "ParamArrayAttribute").Count()
End Function
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesMetadata()
Dim ilSource = <![CDATA[
.assembly extern System {}
.class public C
{
.method public static object F0([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F1([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static object F2([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F3([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
.method public static int32 F4([opt] int32 i)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 01 00 00 00 00 00 ) // [DefaultParameterValue(1)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 02 00 00 00 00 00 ) // [DefaultParameterValue(2)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 03 00 00 00 00 00 ) // [DefaultParameterValue(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.DateTime F5([opt] valuetype [mscorlib]System.DateTime d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 01 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 02 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.Decimal F6([opt] valuetype [mscorlib]System.Decimal d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
}
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F0())
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5().Ticks)
Report(C.F6())
End Sub
Shared Sub Report(o As Object)
Dim value As Object = If (TypeOf o is Date, DirectCast(o, Date).ToString("yyyy-MM-dd HH:mm:ss"), o)
System.Console.WriteLine("{0}: {1}", o.GetType(), value)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, expectedOutput:=<![CDATA[
System.Reflection.Missing: System.Reflection.Missing
System.DateTime: 0001-01-01 00:00:00
System.DateTime: 0001-01-01 00:00:00
System.DateTime: 0001-01-01 00:00:00
System.Int32: 0
System.Int64: 3
System.Decimal: 3
]]>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues()
Dim source1 =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Function F1(Optional o As Integer = 1)
Return o
End Function
Public Shared Function F2(<[Optional](), DefaultParameterValue(2)> o As Integer)
Return o
End Function
Public Shared Function F3(<DefaultParameterValue(3)> Optional o As Integer = 3)
Return o
End Function
Public Shared Function F4(Optional o As Decimal = 4)
Return o
End Function
Public Shared Function F5(<[Optional](), DecimalConstant(0, 0, 0, 0, 5)> o As Decimal)
Return o
End Function
Public Shared Function F6(<DecimalConstant(0, 0, 0, 0, 6)> Optional o As Decimal = 6)
Return o
End Function
Public Shared Function F7(Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Function F8(<[Optional](), DateTimeConstant(635102208000000000)> o As DateTime)
Return o
End Function
Public Shared Function F9(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Property P(<DecimalConstant(0, 0, 0, 0, 10)> Optional o As Decimal = 10)
Get
Return o
End Get
Set
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(source1)
comp1.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp1, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), Nothing, 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DefaultParameterValueAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DefaultParameterValueAttribute", 3, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F4").Parameters(0), "DecimalConstantAttribute", 4UI, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F5").Parameters(0), "DecimalConstantAttribute", 5, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F6").Parameters(0), "DecimalConstantAttribute", 6, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F7").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F8").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F9").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of PropertySymbol)("P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("get_P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("set_P").Parameters(0), "DecimalConstantAttribute", 10, False)
End Sub)
Dim source2 =
<compilation>
<file name="a.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5())
Report(C.F6())
Report(C.F7().Ticks)
Report(C.F8().Ticks)
Report(C.F9().Ticks)
Report(C.P)
End Sub
Shared Sub Report(o As Object)
System.Console.WriteLine(o)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp2a = CreateCompilationWithMscorlib40AndVBRuntime(
source2,
additionalRefs:={New VisualBasicCompilationReference(comp1)},
options:=TestOptions.DebugExe)
comp2a.AssertTheseDiagnostics(
<errors>
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F2(o As Integer) As Object'.
Report(C.F2())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F5(o As Decimal) As Object'.
Report(C.F5())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F8(o As Date) As Object'.
Report(C.F8().Ticks)
~~
</errors>)
Dim comp2b = CreateCompilationWithMscorlib40AndVBRuntime(
source2,
additionalRefs:={MetadataReference.CreateFromImage(comp1.EmitToArray())},
options:=TestOptions.DebugExe)
comp2b.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp2b, expectedOutput:=
<![CDATA[
1
0
3
4
5
6
635102208000000000
635102208000000000
635102208000000000
10
]]>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 1)
End Sub
Private Sub F2(Optional o As Decimal = 2)
End Sub
Private Partial Sub F3(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 1)
End Sub
Private Partial Sub F2(<DecimalConstant(0, 0, 0, 0, 2)> Optional o As Decimal = 2)
End Sub
Private Sub F3(Optional o As DateTime = #7/24/2013#)
End Sub
End Class
]]>
</file>
</compilation>,
options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(comp, symbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), "DefaultParameterValueAttribute", 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DecimalConstantAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
End Sub)
End Sub
Private Shared Sub VerifyDefaultValueAttribute(parameter As ParameterSymbol, expectedAttributeName As String, expectedDefault As Object, hasDefault As Boolean)
Dim attributes = DirectCast(parameter.ContainingModule, PEModuleSymbol).
GetCustomAttributesForToken(DirectCast(parameter, PEParameterSymbol).Handle).
Where(Function(attr) attr.AttributeClass.Name = expectedAttributeName).
ToArray()
If expectedAttributeName Is Nothing Then
Assert.Equal(attributes.Length, 0)
Else
Assert.Equal(attributes.Length, 1)
Dim attribute = DirectCast(attributes(0), VisualBasicAttributeData)
Dim argument = attribute.ConstructorArguments.Last()
Assert.Equal(expectedDefault, argument.Value)
End If
If hasDefault Then
Assert.Equal(expectedDefault, parameter.ExplicitDefaultValue)
End If
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
<DefaultParameterValue(3)> Optional b As Decimal = 4,
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Interface
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(3)> Optional b As Decimal = 4,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
End Sub
Private Partial Sub F9(<DefaultParameterValue(0)> o As Integer)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 2)
End Sub
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Sub
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Partial Sub F1(Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
''' <summary>
''' Should not report differences if either value is bad.
''' </summary>
<WorkItem(529684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529684")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_BadValue()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
Sub M3(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'C' is not defined.
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~
BC37226: The parameter has multiple distinct default values.
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'C' is not defined.
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
~
BC37226: The parameter has multiple distinct default values.
Sub M3(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub TestOptionalAttributeWithoutDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
IntegerUsingOptionalAttribute()
StringUsingOptionalAttribute()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
0
False
]]>)
End Sub
<WorkItem(543076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543076")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestPropertyIntegerOptionalDouble()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DumpMetadata(nothing, "get_PropertyIntegerOptionalDouble")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: get_PropertyIntegerOptionalDouble
Parameter: Type=System.Int32, Name=i, Optional=False, DefaultValue=
Parameter: Type=System.Double, Name=j, Optional=True, DefaultValue=100
]]>)
End Sub
<WorkItem(543093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543093")>
<Fact()>
Public Sub TestIntegerWithDateTimeOptionalValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
IntegerWithDateTimeOptionalValue()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "IntegerWithDateTimeOptionalValue()").WithArguments("Date", "Integer"))
End Sub
<WorkItem(543093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543093")>
<ConditionalFact(GetType(NoIOperationValidation))> ' Disabling for IOperation run due to https://github.com/dotnet/roslyn/issues/26895
Public Sub TestStringWithOptionalDateTimeValue()
' Error when option strict is on
' No error when option strict is off
Dim expectedDiagnostics = {
Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "StringWithOptionalDateTimeValue()").WithArguments("Date", "String"),
Nothing}
Dim i = 0
For Each o In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= o %>
Module Module1
Sub Main()
StringWithOptionalDateTimeValue()
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
Dim diag = expectedDiagnostics(i)
If diag IsNot Nothing Then
comp.VerifyDiagnostics(diag)
Else
comp.VerifyDiagnostics()
End If
i += 1
Next
End Sub
<WorkItem(543139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543139")>
<Fact()>
Public Sub TestOverrideOptionalArgumentFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class CDerived
Inherits CBase
Public Overrides Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
]]>)
End Sub
<WorkItem(543227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543227")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub TestMultipleEnumDefaultValuesFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
TestWithMultipleOptionalEnumValues()
DumpMetadata(nothing, "TestWithMultipleOptionalEnumValues")
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
references:={_classLibrary},
expectedOutput:=<![CDATA[
Member: TestWithMultipleOptionalEnumValues
Parameter: Type=Library+Animal, Name=e1, Optional=True, DefaultValue=Dog
Parameter: Type=Library+Animal, Name=e2, Optional=True, DefaultValue=Cat
]]>)
End Sub
' Test with omitted argument syntax and an error
' Test without omitted argument syntax and an error
<Fact()>
Public Sub TestExplicitConstantAttributesOnFields_Error()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DecimalConstant(0, 0, 0, 0, 0)> Public F0 As DateTime
<DateTimeConstant(0)> Public F1 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
<DateTimeConstant(0)> Public Const F10 As Integer = 0
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F10 As Integer = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub TestExplicitConstantAttributesOnFields_Valid()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DecimalConstantAttribute(0, 128, 0, 0, 7)> Public Const F1 as Decimal = -7
<DateTimeConstantAttribute(634925952000000000)> Public Const F2 as Date = #1/1/2013#
End Class
]]>
</file>
</compilation>)
CompileAndVerify(comp, symbolValidator:=Sub([module] As ModuleSymbol)
Dim peModule = DirectCast([module], PEModuleSymbol)
Dim type = peModule.GlobalNamespace.GetTypeMember("C")
Dim f1 = DirectCast(type.GetMember("F1"), PEFieldSymbol)
Assert.Equal(1, peModule.GetCustomAttributesForToken(f1.Handle).Length)
Dim f2 = DirectCast(type.GetMember("F2"), PEFieldSymbol)
Assert.Equal(1, peModule.GetCustomAttributesForToken(f2.Handle).Length)
End Sub)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Test/Core/Platform/Desktop/TestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if NET472
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Resources.Proprietary;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Win32;
namespace Roslyn.Test.Utilities
{
public static class DesktopTestHelpers
{
public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType)
{
if (assembly == null || interfaceType == null || !interfaceType.IsInterface)
{
throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType));
}
return assembly.GetTypes().Where((t) =>
{
// simplest way to get types that implement mef type
// we might need to actually check whether type export the interface type later
if (t.IsAbstract)
{
return false;
}
var candidate = t.GetInterface(interfaceType.ToString());
return candidate != null && candidate.Equals(interfaceType);
}).ToList();
}
public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type)
{
if (assembly == null || type == null)
{
throw new ArgumentException("Invalid arguments");
}
return (from t in assembly.GetTypes()
where !t.IsAbstract
where type.IsAssignableFrom(t)
select t).ToList();
}
public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName)
{
var analyzerSource = @"
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } }
public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); }
}";
dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location);
var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location);
var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location);
dir.CopyFile(typeof(Memory<>).Assembly.Location);
dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location);
var analyzerCompilation = CSharpCompilation.Create(
assemblyName,
new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
new MetadataReference[]
{
TestMetadata.NetStandard20.mscorlib,
TestMetadata.NetStandard20.netstandard,
TestMetadata.NetStandard20.SystemRuntime,
MetadataReference.CreateFromFile(immutable.Path),
MetadataReference.CreateFromFile(analyzer.Path)
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray());
}
public static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName)
{
var minSystemCollectionsImmutableSource = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")]
namespace System.Collections.Immutable
{
public struct ImmutableArray<T>
{
}
}
";
var minCodeAnalysisSource = @"
using System;
[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")]
namespace Microsoft.CodeAnalysis.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class DiagnosticAnalyzerAttribute : Attribute
{
public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {}
}
public abstract class DiagnosticAnalyzer
{
public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public abstract void Initialize(AnalysisContext context);
}
public abstract class AnalysisContext
{
}
}
namespace Microsoft.CodeAnalysis
{
public sealed class DiagnosticDescriptor
{
}
}
";
var minSystemCollectionsImmutableImage = CSharpCompilation.Create(
"System.Collections.Immutable",
new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) },
new[] { MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime) },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray();
var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage);
var minCodeAnalysisImage = CSharpCompilation.Create(
"Microsoft.CodeAnalysis",
new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) },
new[]
{
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime),
minSystemCollectionsImmutableRef
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray();
var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage);
var analyzerSource = @"
using System;
using System.Collections.ObjectModel;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Win32.SafeHandles;
[DiagnosticAnalyzer(""C#"")]
public class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[]
{
typeof(Win32Exception), // Microsoft.Win32.Primitives
typeof(AppContext), // System.AppContext
typeof(Console), // System.Console
typeof(ValueTuple), // System.ValueTuple
typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo
typeof(Process), // System.Diagnostics.Process
typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars
typeof(ZipArchive), // System.IO.Compression
typeof(ZipFile), // System.IO.Compression.ZipFile
typeof(FileOptions), // System.IO.FileSystem
typeof(FileAttributes), // System.IO.FileSystem.Primitives
typeof(HttpClient), // System.Net.Http
typeof(AuthenticatedStream), // System.Net.Security
typeof(IOControlCode), // System.Net.Sockets
typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation
typeof(SerializationException), // System.Runtime.Serialization.Primitives
typeof(GenericIdentity), // System.Security.Claims
typeof(Aes), // System.Security.Cryptography.Algorithms
typeof(CspParameters), // System.Security.Cryptography.Csp
typeof(AsnEncodedData), // System.Security.Cryptography.Encoding
typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives
typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates
typeof(IXmlLineInfo), // System.Xml.ReaderWriter
typeof(XmlNode), // System.Xml.XmlDocument
typeof(XPathDocument), // System.Xml.XPath
typeof(XDocumentExtensions), // System.Xml.XPath.XDocument
typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages
typeof(ValueTask<>), // System.Threading.Tasks.Extensions
// csc doesn't ship with facades for the following assemblies.
// Analyzers can't use them unless they carry the facade with them.
// typeof(SafePipeHandle), // System.IO.Pipes
// typeof(StackFrame), // System.Diagnostics.StackTrace
// typeof(BindingFlags), // System.Reflection.TypeExtensions
// typeof(AccessControlActions), // System.Security.AccessControl
// typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows
// typeof(Thread), // System.Threading.Thread
}.Length.ToString());
public override void Initialize(AnalysisContext context)
{
}
}";
var analyzerImage = CSharpCompilation.Create(
analyzerAssemblyName,
new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
new MetadataReference[]
{
minCodeAnalysisRef,
minSystemCollectionsImmutableRef,
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.Microsoft_Win32_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_AppContext),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Console),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_ValueTuple),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_FileVersionInfo),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_Process),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_StackTrace),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Globalization_Calendars),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression_ZipFile),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Pipes),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Http),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Security),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Sockets),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Reflection_TypeExtensions),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_InteropServices_RuntimeInformation),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_Serialization_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_AccessControl),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Claims),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Algorithms),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Csp),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Encoding),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_X509Certificates),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Principal_Windows),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Thread),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Tasks_Extensions),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_ReaderWriter),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XmlDocument),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath_XDocument),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Text_Encoding_CodePages)
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray();
return analyzerImage;
}
public static string? GetMSBuildDirectory()
{
var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0";
using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false))
{
if (key != null)
{
var toolsPath = key.GetValue("MSBuildToolsPath");
if (toolsPath != null)
{
return toolsPath.ToString();
}
}
}
return null;
}
}
}
#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.
#if NET472
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Resources.Proprietary;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Win32;
namespace Roslyn.Test.Utilities
{
public static class DesktopTestHelpers
{
public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType)
{
if (assembly == null || interfaceType == null || !interfaceType.IsInterface)
{
throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType));
}
return assembly.GetTypes().Where((t) =>
{
// simplest way to get types that implement mef type
// we might need to actually check whether type export the interface type later
if (t.IsAbstract)
{
return false;
}
var candidate = t.GetInterface(interfaceType.ToString());
return candidate != null && candidate.Equals(interfaceType);
}).ToList();
}
public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type)
{
if (assembly == null || type == null)
{
throw new ArgumentException("Invalid arguments");
}
return (from t in assembly.GetTypes()
where !t.IsAbstract
where type.IsAssignableFrom(t)
select t).ToList();
}
public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName)
{
var analyzerSource = @"
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } }
public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); }
}";
dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location);
var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location);
var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location);
dir.CopyFile(typeof(Memory<>).Assembly.Location);
dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location);
var analyzerCompilation = CSharpCompilation.Create(
assemblyName,
new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
new MetadataReference[]
{
TestMetadata.NetStandard20.mscorlib,
TestMetadata.NetStandard20.netstandard,
TestMetadata.NetStandard20.SystemRuntime,
MetadataReference.CreateFromFile(immutable.Path),
MetadataReference.CreateFromFile(analyzer.Path)
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray());
}
public static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName)
{
var minSystemCollectionsImmutableSource = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")]
namespace System.Collections.Immutable
{
public struct ImmutableArray<T>
{
}
}
";
var minCodeAnalysisSource = @"
using System;
[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")]
namespace Microsoft.CodeAnalysis.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class DiagnosticAnalyzerAttribute : Attribute
{
public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {}
}
public abstract class DiagnosticAnalyzer
{
public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public abstract void Initialize(AnalysisContext context);
}
public abstract class AnalysisContext
{
}
}
namespace Microsoft.CodeAnalysis
{
public sealed class DiagnosticDescriptor
{
}
}
";
var minSystemCollectionsImmutableImage = CSharpCompilation.Create(
"System.Collections.Immutable",
new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) },
new[] { MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime) },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray();
var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage);
var minCodeAnalysisImage = CSharpCompilation.Create(
"Microsoft.CodeAnalysis",
new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) },
new[]
{
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime),
minSystemCollectionsImmutableRef
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray();
var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage);
var analyzerSource = @"
using System;
using System.Collections.ObjectModel;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Win32.SafeHandles;
[DiagnosticAnalyzer(""C#"")]
public class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[]
{
typeof(Win32Exception), // Microsoft.Win32.Primitives
typeof(AppContext), // System.AppContext
typeof(Console), // System.Console
typeof(ValueTuple), // System.ValueTuple
typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo
typeof(Process), // System.Diagnostics.Process
typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars
typeof(ZipArchive), // System.IO.Compression
typeof(ZipFile), // System.IO.Compression.ZipFile
typeof(FileOptions), // System.IO.FileSystem
typeof(FileAttributes), // System.IO.FileSystem.Primitives
typeof(HttpClient), // System.Net.Http
typeof(AuthenticatedStream), // System.Net.Security
typeof(IOControlCode), // System.Net.Sockets
typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation
typeof(SerializationException), // System.Runtime.Serialization.Primitives
typeof(GenericIdentity), // System.Security.Claims
typeof(Aes), // System.Security.Cryptography.Algorithms
typeof(CspParameters), // System.Security.Cryptography.Csp
typeof(AsnEncodedData), // System.Security.Cryptography.Encoding
typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives
typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates
typeof(IXmlLineInfo), // System.Xml.ReaderWriter
typeof(XmlNode), // System.Xml.XmlDocument
typeof(XPathDocument), // System.Xml.XPath
typeof(XDocumentExtensions), // System.Xml.XPath.XDocument
typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages
typeof(ValueTask<>), // System.Threading.Tasks.Extensions
// csc doesn't ship with facades for the following assemblies.
// Analyzers can't use them unless they carry the facade with them.
// typeof(SafePipeHandle), // System.IO.Pipes
// typeof(StackFrame), // System.Diagnostics.StackTrace
// typeof(BindingFlags), // System.Reflection.TypeExtensions
// typeof(AccessControlActions), // System.Security.AccessControl
// typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows
// typeof(Thread), // System.Threading.Thread
}.Length.ToString());
public override void Initialize(AnalysisContext context)
{
}
}";
var analyzerImage = CSharpCompilation.Create(
analyzerAssemblyName,
new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
new MetadataReference[]
{
minCodeAnalysisRef,
minSystemCollectionsImmutableRef,
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.Microsoft_Win32_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_AppContext),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Console),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_ValueTuple),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_FileVersionInfo),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_Process),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_StackTrace),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Globalization_Calendars),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression_ZipFile),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Pipes),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Http),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Security),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Sockets),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Reflection_TypeExtensions),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_InteropServices_RuntimeInformation),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_Serialization_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_AccessControl),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Claims),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Algorithms),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Csp),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Encoding),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Primitives),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_X509Certificates),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Principal_Windows),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Thread),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Tasks_Extensions),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_ReaderWriter),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XmlDocument),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath_XDocument),
MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Text_Encoding_CodePages)
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray();
return analyzerImage;
}
public static string? GetMSBuildDirectory()
{
var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0";
using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false))
{
if (key != null)
{
var toolsPath = key.GetValue("MSBuildToolsPath");
if (toolsPath != null)
{
return toolsPath.ToString();
}
}
}
return null;
}
}
}
#endif
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/Core/Def/Implementation/ChangeSignature/VisualStudioChangeSignatureOptionsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
[ExportWorkspaceService(typeof(IChangeSignatureOptionsService), ServiceLayer.Host), Shared]
internal class VisualStudioChangeSignatureOptionsService : ForegroundThreadAffinitizedObject, IChangeSignatureOptionsService
{
private readonly IClassificationFormatMap _classificationFormatMap;
private readonly ClassificationTypeMap _classificationTypeMap;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioChangeSignatureOptionsService(
IClassificationFormatMapService classificationFormatMapService,
ClassificationTypeMap classificationTypeMap,
IThreadingContext threadingContext) : base(threadingContext)
{
_classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip");
_classificationTypeMap = classificationTypeMap;
}
public ChangeSignatureOptionsResult? GetChangeSignatureOptions(
Document document,
int positionForTypeBinding,
ISymbol symbol,
ParameterConfiguration parameters)
{
this.AssertIsForeground();
var viewModel = new ChangeSignatureDialogViewModel(
parameters,
symbol,
document,
positionForTypeBinding,
_classificationFormatMap,
_classificationTypeMap);
ChangeSignatureLogger.LogChangeSignatureDialogLaunched();
var dialog = new ChangeSignatureDialog(viewModel);
var result = dialog.ShowModal();
if (result.HasValue && result.Value)
{
ChangeSignatureLogger.LogChangeSignatureDialogCommitted();
var signatureChange = new SignatureChange(parameters, viewModel.GetParameterConfiguration());
signatureChange.LogTelemetry();
return new ChangeSignatureOptionsResult(signatureChange, previewChanges: viewModel.PreviewChanges);
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
[ExportWorkspaceService(typeof(IChangeSignatureOptionsService), ServiceLayer.Host), Shared]
internal class VisualStudioChangeSignatureOptionsService : ForegroundThreadAffinitizedObject, IChangeSignatureOptionsService
{
private readonly IClassificationFormatMap _classificationFormatMap;
private readonly ClassificationTypeMap _classificationTypeMap;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioChangeSignatureOptionsService(
IClassificationFormatMapService classificationFormatMapService,
ClassificationTypeMap classificationTypeMap,
IThreadingContext threadingContext) : base(threadingContext)
{
_classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip");
_classificationTypeMap = classificationTypeMap;
}
public ChangeSignatureOptionsResult? GetChangeSignatureOptions(
Document document,
int positionForTypeBinding,
ISymbol symbol,
ParameterConfiguration parameters)
{
this.AssertIsForeground();
var viewModel = new ChangeSignatureDialogViewModel(
parameters,
symbol,
document,
positionForTypeBinding,
_classificationFormatMap,
_classificationTypeMap);
ChangeSignatureLogger.LogChangeSignatureDialogLaunched();
var dialog = new ChangeSignatureDialog(viewModel);
var result = dialog.ShowModal();
if (result.HasValue && result.Value)
{
ChangeSignatureLogger.LogChangeSignatureDialogCommitted();
var signatureChange = new SignatureChange(parameters, viewModel.GetParameterConfiguration());
signatureChange.LogTelemetry();
return new ChangeSignatureOptionsResult(signatureChange, previewChanges: viewModel.PreviewChanges);
}
return null;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class ConstructorInitializerPlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public ConstructorInitializerPlacementDiagnosticAnalyzer()
: base(IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId,
EnforceOnBuildValues.ConsecutiveBracePlacement,
CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Blank_line_not_allowed_after_constructor_initializer_colon), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer);
if (option.Value)
return;
Recurse(context, option.Notification.Severity, context.Tree.GetRoot(context.CancellationToken));
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node)
{
context.CancellationToken.ThrowIfCancellationRequested();
// Don't bother analyzing nodes that have syntax errors in them.
if (node.ContainsDiagnostics)
return;
if (node is ConstructorInitializerSyntax initializer)
ProcessConstructorInitializer(context, severity, initializer);
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
Recurse(context, severity, child.AsNode()!);
}
}
private void ProcessConstructorInitializer(
SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ConstructorInitializerSyntax initializer)
{
var sourceText = context.Tree.GetText(context.CancellationToken);
var colonToken = initializer.ColonToken;
var thisOrBaseKeyword = initializer.ThisOrBaseKeyword;
var colonLine = sourceText.Lines.GetLineFromPosition(colonToken.SpanStart);
var thisBaseLine = sourceText.Lines.GetLineFromPosition(thisOrBaseKeyword.SpanStart);
if (colonLine == thisBaseLine)
return;
if (colonToken.TrailingTrivia.Count == 0)
return;
if (colonToken.TrailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia)
return;
if (colonToken.TrailingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine()))
return;
if (thisOrBaseKeyword.LeadingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine() && !t.IsSingleOrMultiLineComment()))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
colonToken.GetLocation(),
severity,
additionalLocations: ImmutableArray.Create(initializer.GetLocation()),
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 System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class ConstructorInitializerPlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public ConstructorInitializerPlacementDiagnosticAnalyzer()
: base(IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId,
EnforceOnBuildValues.ConsecutiveBracePlacement,
CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Blank_line_not_allowed_after_constructor_initializer_colon), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer);
if (option.Value)
return;
Recurse(context, option.Notification.Severity, context.Tree.GetRoot(context.CancellationToken));
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node)
{
context.CancellationToken.ThrowIfCancellationRequested();
// Don't bother analyzing nodes that have syntax errors in them.
if (node.ContainsDiagnostics)
return;
if (node is ConstructorInitializerSyntax initializer)
ProcessConstructorInitializer(context, severity, initializer);
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
Recurse(context, severity, child.AsNode()!);
}
}
private void ProcessConstructorInitializer(
SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ConstructorInitializerSyntax initializer)
{
var sourceText = context.Tree.GetText(context.CancellationToken);
var colonToken = initializer.ColonToken;
var thisOrBaseKeyword = initializer.ThisOrBaseKeyword;
var colonLine = sourceText.Lines.GetLineFromPosition(colonToken.SpanStart);
var thisBaseLine = sourceText.Lines.GetLineFromPosition(thisOrBaseKeyword.SpanStart);
if (colonLine == thisBaseLine)
return;
if (colonToken.TrailingTrivia.Count == 0)
return;
if (colonToken.TrailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia)
return;
if (colonToken.TrailingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine()))
return;
if (thisOrBaseKeyword.LeadingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine() && !t.IsSingleOrMultiLineComment()))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
colonToken.GetLocation(),
severity,
additionalLocations: ImmutableArray.Create(initializer.GetLocation()),
properties: null));
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/Symbols/IMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a method or method-like symbol (including constructor,
/// destructor, operator, or property/event accessor).
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IMethodSymbol : ISymbol
{
/// <summary>
/// Gets what kind of method this is. There are several different kinds of things in the
/// C# language that are represented as methods. This property allow distinguishing those things
/// without having to decode the name of the method.
/// </summary>
MethodKind MethodKind { get; }
/// <summary>
/// Returns the arity of this method, or the number of type parameters it takes.
/// A non-generic method has zero arity.
/// </summary>
int Arity { get; }
/// <summary>
/// Returns whether this method is generic; i.e., does it have any type parameters?
/// </summary>
bool IsGenericMethod { get; }
/// <summary>
/// Returns true if this method is an extension method.
/// </summary>
bool IsExtensionMethod { get; }
/// <summary>
/// Returns true if this method is an async method
/// </summary>
bool IsAsync { get; }
/// <summary>
/// Returns whether this method is using CLI VARARG calling convention. This is used for
/// C-style variable argument lists. This is used extremely rarely in C# code and is
/// represented using the undocumented "__arglist" keyword.
///
/// Note that methods with "params" on the last parameter are indicated with the "IsParams"
/// property on ParameterSymbol, and are not represented with this property.
/// </summary>
bool IsVararg { get; }
/// <summary>
/// Returns whether this built-in operator checks for integer overflow.
/// </summary>
bool IsCheckedBuiltin { get; }
/// <summary>
/// Returns true if this method hides base methods by name. This cannot be specified directly
/// in the C# language, but can be true for methods defined in other languages imported from
/// metadata. The equivalent of the "hidebyname" flag in metadata.
/// </summary>
bool HidesBaseMethodsByName { get; }
/// <summary>
/// Returns true if this method has no return type; i.e., returns "void".
/// </summary>
bool ReturnsVoid { get; }
/// <summary>
/// Returns true if this method returns by reference.
/// </summary>
bool ReturnsByRef { get; }
/// <summary>
/// Returns true if this method returns by ref readonly.
/// </summary>
bool ReturnsByRefReadonly { get; }
/// <summary>
/// Returns the RefKind of the method.
/// </summary>
RefKind RefKind { get; }
/// <summary>
/// Gets the return type of the method.
/// </summary>
ITypeSymbol ReturnType { get; }
/// <summary>
/// Gets the top-level nullability of the return type of the method.
/// </summary>
NullableAnnotation ReturnNullableAnnotation { get; }
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a given type parameter,
/// then the type parameter itself is consider the type argument.
/// </summary>
ImmutableArray<ITypeSymbol> TypeArguments { get; }
/// <summary>
/// Returns the top-level nullability of the type arguments that have been substituted
/// for the type parameters. If nothing has been substituted for a given type parameter,
/// then <see cref="NullableAnnotation.None"/> is returned.
/// </summary>
ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; }
/// <summary>
/// Get the type parameters on this method. If the method has not generic,
/// returns an empty list.
/// </summary>
ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
/// <summary>
/// Gets the parameters of this method. If this method has no parameters, returns
/// an empty list.
/// </summary>
ImmutableArray<IParameterSymbol> Parameters { get; }
/// <summary>
/// Returns the method symbol that this method was constructed from. The resulting
/// method symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
IMethodSymbol ConstructedFrom { get; }
/// <summary>
/// Indicates whether the method is readonly,
/// i.e. whether the 'this' receiver parameter is 'ref readonly'.
/// Returns true for readonly instance methods and accessors
/// and for reduced extension methods with a 'this in' parameter.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true for 'init' set accessors, and false otherwise.
/// </summary>
bool IsInitOnly { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IMethodSymbol OriginalDefinition { get; }
/// <summary>
/// If this method overrides another method (because it both had the override modifier
/// and there correctly was a method to override), returns the overridden method.
/// </summary>
IMethodSymbol? OverriddenMethod { get; }
/// <summary>
/// If this method can be applied to an object, returns the type of object it is applied to.
/// </summary>
ITypeSymbol? ReceiverType { get; }
/// <summary>
/// If this method can be applied to an object, returns the top-level nullability of the object it is applied to.
/// </summary>
NullableAnnotation ReceiverNullableAnnotation { get; }
/// <summary>
/// If this method is a reduced extension method, returns the definition of extension
/// method from which this was reduced. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReducedFrom { get; }
/// <summary>
/// If this method is a reduced extension method, returns a type inferred during reduction process for the type parameter.
/// </summary>
/// <param name="reducedFromTypeParameter">Type parameter of the corresponding <see cref="ReducedFrom"/> method.</param>
/// <returns>Inferred type or Nothing if nothing was inferred.</returns>
/// <exception cref="System.InvalidOperationException">If this is not a reduced extension method.</exception>
/// <exception cref="System.ArgumentNullException">If <paramref name="reducedFromTypeParameter"/> is null.</exception>
/// <exception cref="System.ArgumentException">If <paramref name="reducedFromTypeParameter"/> doesn't belong to the corresponding <see cref="ReducedFrom"/> method.</exception>
ITypeSymbol? GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
/// <summary>
/// If this is an extension method that can be applied to a receiver of the given type,
/// returns a reduced extension method symbol thus formed. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReduceExtensionMethod(ITypeSymbol receiverType);
/// <summary>
/// Returns interface methods explicitly implemented by this method.
/// </summary>
/// <remarks>
/// Methods imported from metadata can explicitly implement more than one method,
/// that is why return type is ImmutableArray.
/// </remarks>
ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
/// <summary>
/// Returns the list of custom modifiers, if any, associated with the return type.
/// </summary>
ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get; }
/// <summary>
/// Custom modifiers associated with the ref modifier, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> RefCustomModifiers { get; }
/// <summary>
/// Returns the list of custom attributes, if any, associated with the returned value.
/// </summary>
ImmutableArray<AttributeData> GetReturnTypeAttributes();
/// <summary>
/// The calling convention enum of the method symbol.
/// </summary>
SignatureCallingConvention CallingConvention { get; }
/// <summary>
/// Modifier types that are considered part of the calling convention of this method, if the <see cref="MethodKind"/> is <see cref="MethodKind.FunctionPointerSignature"/>
/// and the <see cref="CallingConvention"/> is <see cref="SignatureCallingConvention.Unmanaged"/>. If this is not a function pointer signature or the calling convention is
/// not unmanaged, this is an empty array. Order and duplication of these modifiers reflect source/metadata order and duplication, whichever this symbol came from.
/// </summary>
ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes { get; }
/// <summary>
/// Returns a symbol (e.g. property, event, etc.) associated with the method.
/// </summary>
/// <remarks>
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.PropertyGet"/> or <see cref="MethodKind.PropertySet"/>,
/// returns the property that this method is the getter or setter for.
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.EventAdd"/> or <see cref="MethodKind.EventRemove"/>,
/// returns the event that this method is the adder or remover for.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </remarks>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns a constructed method given its type arguments.
/// </summary>
/// <param name="typeArguments">The immediate type arguments to be replaced for type
/// parameters in the method.</param>
IMethodSymbol Construct(params ITypeSymbol[] typeArguments);
/// <summary>
/// Returns a constructed method given its type arguments and type argument nullable annotations.
/// </summary>
IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations);
/// <summary>
/// If this is a partial method implementation part, returns the corresponding
/// definition part. Otherwise null.
/// </summary>
IMethodSymbol? PartialDefinitionPart { get; }
/// <summary>
/// If this is a partial method declaration without a body, and the method is
/// implemented with a body, returns that implementing definition. Otherwise
/// null.
/// </summary>
IMethodSymbol? PartialImplementationPart { get; }
/// <summary>
/// Returns the implementation flags for the given method symbol.
/// </summary>
MethodImplAttributes MethodImplementationFlags { get; }
/// <summary>
/// Return true if this is a partial method definition without a body. If there
/// is an implementing body, it can be retrieved with <see cref="PartialImplementationPart"/>.
/// </summary>
bool IsPartialDefinition { get; }
/// <summary>
/// Platform invoke information, or null if the method isn't a P/Invoke.
/// </summary>
DllImportData? GetDllImportData();
/// <summary>
/// If this method is a Lambda method (MethodKind = MethodKind.LambdaMethod) and
/// there is an anonymous delegate associated with it, returns this delegate.
///
/// Returns null if the symbol is not a lambda or if it does not have an
/// anonymous delegate associated with it.
/// </summary>
INamedTypeSymbol? AssociatedAnonymousDelegate { get; }
/// <summary>
/// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute.
/// </summary>
bool IsConditional { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a method or method-like symbol (including constructor,
/// destructor, operator, or property/event accessor).
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IMethodSymbol : ISymbol
{
/// <summary>
/// Gets what kind of method this is. There are several different kinds of things in the
/// C# language that are represented as methods. This property allow distinguishing those things
/// without having to decode the name of the method.
/// </summary>
MethodKind MethodKind { get; }
/// <summary>
/// Returns the arity of this method, or the number of type parameters it takes.
/// A non-generic method has zero arity.
/// </summary>
int Arity { get; }
/// <summary>
/// Returns whether this method is generic; i.e., does it have any type parameters?
/// </summary>
bool IsGenericMethod { get; }
/// <summary>
/// Returns true if this method is an extension method.
/// </summary>
bool IsExtensionMethod { get; }
/// <summary>
/// Returns true if this method is an async method
/// </summary>
bool IsAsync { get; }
/// <summary>
/// Returns whether this method is using CLI VARARG calling convention. This is used for
/// C-style variable argument lists. This is used extremely rarely in C# code and is
/// represented using the undocumented "__arglist" keyword.
///
/// Note that methods with "params" on the last parameter are indicated with the "IsParams"
/// property on ParameterSymbol, and are not represented with this property.
/// </summary>
bool IsVararg { get; }
/// <summary>
/// Returns whether this built-in operator checks for integer overflow.
/// </summary>
bool IsCheckedBuiltin { get; }
/// <summary>
/// Returns true if this method hides base methods by name. This cannot be specified directly
/// in the C# language, but can be true for methods defined in other languages imported from
/// metadata. The equivalent of the "hidebyname" flag in metadata.
/// </summary>
bool HidesBaseMethodsByName { get; }
/// <summary>
/// Returns true if this method has no return type; i.e., returns "void".
/// </summary>
bool ReturnsVoid { get; }
/// <summary>
/// Returns true if this method returns by reference.
/// </summary>
bool ReturnsByRef { get; }
/// <summary>
/// Returns true if this method returns by ref readonly.
/// </summary>
bool ReturnsByRefReadonly { get; }
/// <summary>
/// Returns the RefKind of the method.
/// </summary>
RefKind RefKind { get; }
/// <summary>
/// Gets the return type of the method.
/// </summary>
ITypeSymbol ReturnType { get; }
/// <summary>
/// Gets the top-level nullability of the return type of the method.
/// </summary>
NullableAnnotation ReturnNullableAnnotation { get; }
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a given type parameter,
/// then the type parameter itself is consider the type argument.
/// </summary>
ImmutableArray<ITypeSymbol> TypeArguments { get; }
/// <summary>
/// Returns the top-level nullability of the type arguments that have been substituted
/// for the type parameters. If nothing has been substituted for a given type parameter,
/// then <see cref="NullableAnnotation.None"/> is returned.
/// </summary>
ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; }
/// <summary>
/// Get the type parameters on this method. If the method has not generic,
/// returns an empty list.
/// </summary>
ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
/// <summary>
/// Gets the parameters of this method. If this method has no parameters, returns
/// an empty list.
/// </summary>
ImmutableArray<IParameterSymbol> Parameters { get; }
/// <summary>
/// Returns the method symbol that this method was constructed from. The resulting
/// method symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
IMethodSymbol ConstructedFrom { get; }
/// <summary>
/// Indicates whether the method is readonly,
/// i.e. whether the 'this' receiver parameter is 'ref readonly'.
/// Returns true for readonly instance methods and accessors
/// and for reduced extension methods with a 'this in' parameter.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true for 'init' set accessors, and false otherwise.
/// </summary>
bool IsInitOnly { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IMethodSymbol OriginalDefinition { get; }
/// <summary>
/// If this method overrides another method (because it both had the override modifier
/// and there correctly was a method to override), returns the overridden method.
/// </summary>
IMethodSymbol? OverriddenMethod { get; }
/// <summary>
/// If this method can be applied to an object, returns the type of object it is applied to.
/// </summary>
ITypeSymbol? ReceiverType { get; }
/// <summary>
/// If this method can be applied to an object, returns the top-level nullability of the object it is applied to.
/// </summary>
NullableAnnotation ReceiverNullableAnnotation { get; }
/// <summary>
/// If this method is a reduced extension method, returns the definition of extension
/// method from which this was reduced. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReducedFrom { get; }
/// <summary>
/// If this method is a reduced extension method, returns a type inferred during reduction process for the type parameter.
/// </summary>
/// <param name="reducedFromTypeParameter">Type parameter of the corresponding <see cref="ReducedFrom"/> method.</param>
/// <returns>Inferred type or Nothing if nothing was inferred.</returns>
/// <exception cref="System.InvalidOperationException">If this is not a reduced extension method.</exception>
/// <exception cref="System.ArgumentNullException">If <paramref name="reducedFromTypeParameter"/> is null.</exception>
/// <exception cref="System.ArgumentException">If <paramref name="reducedFromTypeParameter"/> doesn't belong to the corresponding <see cref="ReducedFrom"/> method.</exception>
ITypeSymbol? GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
/// <summary>
/// If this is an extension method that can be applied to a receiver of the given type,
/// returns a reduced extension method symbol thus formed. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReduceExtensionMethod(ITypeSymbol receiverType);
/// <summary>
/// Returns interface methods explicitly implemented by this method.
/// </summary>
/// <remarks>
/// Methods imported from metadata can explicitly implement more than one method,
/// that is why return type is ImmutableArray.
/// </remarks>
ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
/// <summary>
/// Returns the list of custom modifiers, if any, associated with the return type.
/// </summary>
ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get; }
/// <summary>
/// Custom modifiers associated with the ref modifier, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> RefCustomModifiers { get; }
/// <summary>
/// Returns the list of custom attributes, if any, associated with the returned value.
/// </summary>
ImmutableArray<AttributeData> GetReturnTypeAttributes();
/// <summary>
/// The calling convention enum of the method symbol.
/// </summary>
SignatureCallingConvention CallingConvention { get; }
/// <summary>
/// Modifier types that are considered part of the calling convention of this method, if the <see cref="MethodKind"/> is <see cref="MethodKind.FunctionPointerSignature"/>
/// and the <see cref="CallingConvention"/> is <see cref="SignatureCallingConvention.Unmanaged"/>. If this is not a function pointer signature or the calling convention is
/// not unmanaged, this is an empty array. Order and duplication of these modifiers reflect source/metadata order and duplication, whichever this symbol came from.
/// </summary>
ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes { get; }
/// <summary>
/// Returns a symbol (e.g. property, event, etc.) associated with the method.
/// </summary>
/// <remarks>
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.PropertyGet"/> or <see cref="MethodKind.PropertySet"/>,
/// returns the property that this method is the getter or setter for.
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.EventAdd"/> or <see cref="MethodKind.EventRemove"/>,
/// returns the event that this method is the adder or remover for.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </remarks>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns a constructed method given its type arguments.
/// </summary>
/// <param name="typeArguments">The immediate type arguments to be replaced for type
/// parameters in the method.</param>
IMethodSymbol Construct(params ITypeSymbol[] typeArguments);
/// <summary>
/// Returns a constructed method given its type arguments and type argument nullable annotations.
/// </summary>
IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations);
/// <summary>
/// If this is a partial method implementation part, returns the corresponding
/// definition part. Otherwise null.
/// </summary>
IMethodSymbol? PartialDefinitionPart { get; }
/// <summary>
/// If this is a partial method declaration without a body, and the method is
/// implemented with a body, returns that implementing definition. Otherwise
/// null.
/// </summary>
IMethodSymbol? PartialImplementationPart { get; }
/// <summary>
/// Returns the implementation flags for the given method symbol.
/// </summary>
MethodImplAttributes MethodImplementationFlags { get; }
/// <summary>
/// Return true if this is a partial method definition without a body. If there
/// is an implementing body, it can be retrieved with <see cref="PartialImplementationPart"/>.
/// </summary>
bool IsPartialDefinition { get; }
/// <summary>
/// Platform invoke information, or null if the method isn't a P/Invoke.
/// </summary>
DllImportData? GetDllImportData();
/// <summary>
/// If this method is a Lambda method (MethodKind = MethodKind.LambdaMethod) and
/// there is an anonymous delegate associated with it, returns this delegate.
///
/// Returns null if the symbol is not a lambda or if it does not have an
/// anonymous delegate associated with it.
/// </summary>
INamedTypeSymbol? AssociatedAnonymousDelegate { get; }
/// <summary>
/// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute.
/// </summary>
bool IsConditional { get; }
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Test/Core/Platform/Custom/SigningTestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Interop;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
internal static class SigningTestHelpers
{
public static readonly StrongNameProvider DefaultDesktopStrongNameProvider =
new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem());
// these are virtual paths that don't exist on disk
internal static readonly string KeyFileDirectory = ExecutionConditionUtil.IsWindows
? @"R:\__Test__\"
: "/r/__Test__/";
internal static readonly string KeyPairFile = KeyFileDirectory + @"KeyPair_" + Guid.NewGuid() + ".snk";
internal static readonly string PublicKeyFile = KeyFileDirectory + @"PublicKey_" + Guid.NewGuid() + ".snk";
internal static readonly string KeyPairFile2 = KeyFileDirectory + @"KeyPair2_" + Guid.NewGuid() + ".snk";
internal static readonly string PublicKeyFile2 = KeyFileDirectory + @"PublicKey2_" + Guid.NewGuid() + ".snk";
internal static readonly string MaxSizeKeyFile = KeyFileDirectory + @"MaxSizeKey_" + Guid.NewGuid() + ".snk";
private static bool s_keyInstalled;
internal const string TestContainerName = "RoslynTestContainer";
internal static readonly ImmutableArray<byte> PublicKey = ImmutableArray.Create(TestResources.General.snPublicKey);
internal static object s_keyInstalledLock = new object();
/// <summary>
/// Installs the keys used for testing into the machine cache on Windows.
/// </summary>
internal static unsafe void InstallKey()
{
if (ExecutionConditionUtil.IsWindows)
{
lock (s_keyInstalledLock)
{
if (!s_keyInstalled)
{
InstallKey(TestResources.General.snKey, TestContainerName);
s_keyInstalled = true;
}
}
}
}
private static unsafe void InstallKey(byte[] keyBlob, string keyName)
{
try
{
IClrStrongName strongName = new DesktopStrongNameProvider().GetStrongNameInterface();
//EDMAURER use marshal to be safe?
fixed (byte* p = keyBlob)
{
strongName.StrongNameKeyInstall(keyName, (IntPtr)p, keyBlob.Length);
}
}
catch (COMException ex)
{
if (unchecked((uint)ex.ErrorCode) != 0x8009000F)
throw;
}
}
internal sealed class VirtualizedStrongNameFileSystem : StrongNameFileSystem
{
internal VirtualizedStrongNameFileSystem(string tempPath = null) : base(tempPath)
{
}
private static bool PathEquals(string left, string right)
{
return string.Equals(
FileUtilities.NormalizeAbsolutePath(left),
FileUtilities.NormalizeAbsolutePath(right),
StringComparison.OrdinalIgnoreCase);
}
internal override bool FileExists(string fullPath)
{
return PathEquals(fullPath, KeyPairFile) || PathEquals(fullPath, PublicKeyFile);
}
internal override byte[] ReadAllBytes(string fullPath)
{
if (PathEquals(fullPath, KeyPairFile))
{
return TestResources.General.snKey;
}
else if (PathEquals(fullPath, PublicKeyFile))
{
return TestResources.General.snPublicKey;
}
else if (PathEquals(fullPath, KeyPairFile2))
{
return TestResources.General.snKey2;
}
else if (PathEquals(fullPath, PublicKeyFile2))
{
return TestResources.General.snPublicKey2;
}
else if (PathEquals(fullPath, MaxSizeKeyFile))
{
return TestResources.General.snMaxSizeKey;
}
throw new FileNotFoundException("File not found", fullPath);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Interop;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
internal static class SigningTestHelpers
{
public static readonly StrongNameProvider DefaultDesktopStrongNameProvider =
new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem());
// these are virtual paths that don't exist on disk
internal static readonly string KeyFileDirectory = ExecutionConditionUtil.IsWindows
? @"R:\__Test__\"
: "/r/__Test__/";
internal static readonly string KeyPairFile = KeyFileDirectory + @"KeyPair_" + Guid.NewGuid() + ".snk";
internal static readonly string PublicKeyFile = KeyFileDirectory + @"PublicKey_" + Guid.NewGuid() + ".snk";
internal static readonly string KeyPairFile2 = KeyFileDirectory + @"KeyPair2_" + Guid.NewGuid() + ".snk";
internal static readonly string PublicKeyFile2 = KeyFileDirectory + @"PublicKey2_" + Guid.NewGuid() + ".snk";
internal static readonly string MaxSizeKeyFile = KeyFileDirectory + @"MaxSizeKey_" + Guid.NewGuid() + ".snk";
private static bool s_keyInstalled;
internal const string TestContainerName = "RoslynTestContainer";
internal static readonly ImmutableArray<byte> PublicKey = ImmutableArray.Create(TestResources.General.snPublicKey);
internal static object s_keyInstalledLock = new object();
/// <summary>
/// Installs the keys used for testing into the machine cache on Windows.
/// </summary>
internal static unsafe void InstallKey()
{
if (ExecutionConditionUtil.IsWindows)
{
lock (s_keyInstalledLock)
{
if (!s_keyInstalled)
{
InstallKey(TestResources.General.snKey, TestContainerName);
s_keyInstalled = true;
}
}
}
}
private static unsafe void InstallKey(byte[] keyBlob, string keyName)
{
try
{
IClrStrongName strongName = new DesktopStrongNameProvider().GetStrongNameInterface();
//EDMAURER use marshal to be safe?
fixed (byte* p = keyBlob)
{
strongName.StrongNameKeyInstall(keyName, (IntPtr)p, keyBlob.Length);
}
}
catch (COMException ex)
{
if (unchecked((uint)ex.ErrorCode) != 0x8009000F)
throw;
}
}
internal sealed class VirtualizedStrongNameFileSystem : StrongNameFileSystem
{
internal VirtualizedStrongNameFileSystem(string tempPath = null) : base(tempPath)
{
}
private static bool PathEquals(string left, string right)
{
return string.Equals(
FileUtilities.NormalizeAbsolutePath(left),
FileUtilities.NormalizeAbsolutePath(right),
StringComparison.OrdinalIgnoreCase);
}
internal override bool FileExists(string fullPath)
{
return PathEquals(fullPath, KeyPairFile) || PathEquals(fullPath, PublicKeyFile);
}
internal override byte[] ReadAllBytes(string fullPath)
{
if (PathEquals(fullPath, KeyPairFile))
{
return TestResources.General.snKey;
}
else if (PathEquals(fullPath, PublicKeyFile))
{
return TestResources.General.snPublicKey;
}
else if (PathEquals(fullPath, KeyPairFile2))
{
return TestResources.General.snKey2;
}
else if (PathEquals(fullPath, PublicKeyFile2))
{
return TestResources.General.snPublicKey2;
}
else if (PathEquals(fullPath, MaxSizeKeyFile))
{
return TestResources.General.snMaxSizeKey;
}
throw new FileNotFoundException("File not found", fullPath);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/Symbols/SymbolVisitor`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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class CSharpSymbolVisitor<TResult>
{
public virtual TResult Visit(Symbol symbol)
{
return (object)symbol == null
? default(TResult)
: symbol.Accept(this);
}
public virtual TResult DefaultVisit(Symbol symbol)
{
return default(TResult);
}
public virtual TResult VisitAlias(AliasSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitArrayType(ArrayTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitAssembly(AssemblySymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitDiscard(DiscardSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitEvent(EventSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitField(FieldSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitLabel(LabelSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitLocal(LocalSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitMethod(MethodSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitModule(ModuleSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitNamedType(NamedTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitNamespace(NamespaceSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitParameter(ParameterSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitPointerType(PointerTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitProperty(PropertySymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol)
{
return DefaultVisit(symbol);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class CSharpSymbolVisitor<TResult>
{
public virtual TResult Visit(Symbol symbol)
{
return (object)symbol == null
? default(TResult)
: symbol.Accept(this);
}
public virtual TResult DefaultVisit(Symbol symbol)
{
return default(TResult);
}
public virtual TResult VisitAlias(AliasSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitArrayType(ArrayTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitAssembly(AssemblySymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitDiscard(DiscardSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitEvent(EventSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitField(FieldSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitLabel(LabelSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitLocal(LocalSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitMethod(MethodSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitModule(ModuleSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitNamedType(NamedTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitNamespace(NamespaceSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitParameter(ParameterSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitPointerType(PointerTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitProperty(PropertySymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol)
{
return DefaultVisit(symbol);
}
public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol)
{
return DefaultVisit(symbol);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayLocalOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the options for how locals are displayed in the description of a symbol.
/// </summary>
[Flags]
public enum SymbolDisplayLocalOptions
{
/// <summary>
/// Shows only the name of the local.
/// For example, "x".
/// </summary>
None = 0,
/// <summary>
/// Shows the type of the local in addition to its name.
/// For example, "int x" in C# or "x As Integer" in Visual Basic.
/// </summary>
IncludeType = 1 << 0,
/// <summary>
/// Shows the constant value of the local, if there is one, in addition to its name.
/// For example "x = 1".
/// </summary>
IncludeConstantValue = 1 << 1,
/// <summary>
/// Includes the <c>ref</c> keyword for ref-locals.
/// </summary>
IncludeRef = 1 << 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the options for how locals are displayed in the description of a symbol.
/// </summary>
[Flags]
public enum SymbolDisplayLocalOptions
{
/// <summary>
/// Shows only the name of the local.
/// For example, "x".
/// </summary>
None = 0,
/// <summary>
/// Shows the type of the local in addition to its name.
/// For example, "int x" in C# or "x As Integer" in Visual Basic.
/// </summary>
IncludeType = 1 << 0,
/// <summary>
/// Shows the constant value of the local, if there is one, in addition to its name.
/// For example "x = 1".
/// </summary>
IncludeConstantValue = 1 << 1,
/// <summary>
/// Includes the <c>ref</c> keyword for ref-locals.
/// </summary>
IncludeRef = 1 << 2,
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/VisualBasic/Portable/Lowering/ExpressionLambdaRewriter/ExpressionLambdaRewriter_BinaryOperator.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class ExpressionLambdaRewriter
Private Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundExpression
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
Select Case node.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.And,
BinaryOperatorKind.Or,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Power,
BinaryOperatorKind.Multiply,
BinaryOperatorKind.Add,
BinaryOperatorKind.Subtract,
BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.Concatenate,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift
Return ConvertBinaryOperator(node)
Case BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan
Return ConvertBooleanOperator(node)
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso
Return ConvertShortCircuitedBooleanOperator(node)
Case BinaryOperatorKind.Like
' Like operator should already be rewritten by this time
Throw ExceptionUtilities.UnexpectedValue(node.OperatorKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.OperatorKind)
End Select
End Function
Private Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundExpression
Dim opKind As BinaryOperatorKind = node.OperatorKind And BinaryOperatorKind.OpMask
Dim isLifted As Boolean = (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(node.Call.Method.ReturnType)
Select Case opKind
Case BinaryOperatorKind.Like,
BinaryOperatorKind.Concatenate
Return ConvertUserDefinedLikeOrConcate(node)
Case BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan
' Error should have been reported by DiagnosticsPass, see
' DiagnosticsPass.VisitUserDefinedBinaryOperator
Debug.Assert(Not isLifted OrElse Not node.Call.Method.ReturnType.IsNullableType)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, isChecked),
Visit(node.Left), Visit(node.Right),
Me._factory.Literal(isLifted),
_factory.MethodInfo(node.Call.Method))
Case Else
' Error should have been reported by DiagnosticsPass, see
' DiagnosticsPass.VisitUserDefinedBinaryOperator
Debug.Assert(Not isLifted OrElse Not node.Call.Method.ReturnType.IsNullableType)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, isChecked),
Visit(node.Left), Visit(node.Right),
_factory.MethodInfo(node.Call.Method))
End Select
End Function
Private Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundExpression
Dim operand As BoundUserDefinedBinaryOperator = node.BitwiseOperator
Dim opKind As BinaryOperatorKind = operand.OperatorKind And BinaryOperatorKind.OpMask
' See comment in DiagnosticsPass.VisitUserDefinedShortCircuitingOperator
Debug.Assert(operand.Call.Method.ReturnType.IsSameTypeIgnoringAll(operand.Call.Method.Parameters(0).Type) AndAlso
operand.Call.Method.ReturnType.IsSameTypeIgnoringAll(operand.Call.Method.Parameters(1).Type))
opKind = If(opKind = BinaryOperatorKind.And, BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, False),
Visit(operand.Left), Visit(operand.Right),
_factory.MethodInfo(operand.Call.Method))
End Function
#Region "User Defined Like"
Private Function ConvertUserDefinedLikeOrConcate(node As BoundUserDefinedBinaryOperator) As BoundExpression
Dim [call] As BoundCall = node.Call
Dim opKind As BinaryOperatorKind = node.OperatorKind
If (opKind And BinaryOperatorKind.Lifted) = 0 Then
Return VisitInternal([call])
End If
Return VisitInternal(AdjustCallForLiftedOperator(opKind, [call], node.Type))
End Function
#End Region
#Region "Is, IsNot, <, <=, >=, >"
Private Function ConvertBooleanOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultNotNullableType As TypeSymbol = resultType.GetNullableUnderlyingTypeOrSelf
Dim resultUnderlyingType As TypeSymbol = resultNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot OrElse
opKind = BinaryOperatorKind.Equals OrElse opKind = BinaryOperatorKind.NotEquals OrElse
opKind = BinaryOperatorKind.LessThan OrElse opKind = BinaryOperatorKind.GreaterThan OrElse
opKind = BinaryOperatorKind.LessThanOrEqual OrElse opKind = BinaryOperatorKind.GreaterThanOrEqual)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
' Prepare left and right
Dim originalLeft As BoundExpression = node.Left
Dim operandType As TypeSymbol = originalLeft.Type
Dim left As BoundExpression = Nothing
Dim originalRight As BoundExpression = node.Right
Dim right As BoundExpression = Nothing
Dim isIsIsNot As Boolean = (opKind = BinaryOperatorKind.Is) OrElse (opKind = BinaryOperatorKind.IsNot)
If isIsIsNot Then
' Ensure Nothing literals is converted to the type of an opposite operand
If originalLeft.IsNothingLiteral Then
If originalRight.Type.IsNullableType Then
Debug.Assert(originalLeft.Type Is Nothing OrElse originalLeft.Type.IsObjectType)
left = CreateLiteralExpression(originalLeft, originalRight.Type)
operandType = originalRight.Type
End If
ElseIf originalRight.IsNothingLiteral Then
If originalLeft.Type.IsNullableType Then
Debug.Assert(originalRight.Type Is Nothing OrElse originalRight.Type.IsObjectType)
right = CreateLiteralExpression(originalRight, originalLeft.Type)
End If
End If
End If
Dim operandIsNullable As Boolean = operandType.IsNullableType
Dim operandNotNullableType As TypeSymbol = operandType.GetNullableUnderlyingTypeOrSelf
Dim operandUnderlyingType As TypeSymbol = operandNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim operandUnderlyingSpecialType As SpecialType = operandUnderlyingType.SpecialType
If left Is Nothing Then
left = Visit(originalLeft)
Debug.Assert(TypeSymbol.Equals(operandType, originalLeft.Type, TypeCompareKind.ConsiderEverything))
End If
If right Is Nothing Then
right = Visit(originalRight)
Debug.Assert(TypeSymbol.Equals(operandType, originalRight.Type, TypeCompareKind.ConsiderEverything))
End If
' Do we need to handle special cases?
Dim helper As MethodSymbol = Nothing
' [>|>=|<|<=] with System.Object argument should already be rewritten into proper calls
Debug.Assert(operandUnderlyingSpecialType <> SpecialType.System_Object OrElse isIsIsNot)
' All boolean operators with System.String argument should already be rewritten into proper calls
Debug.Assert(operandUnderlyingSpecialType <> SpecialType.System_String)
If operandUnderlyingSpecialType = SpecialType.System_Decimal Then
helper = GetHelperForDecimalBinaryOperation(opKind)
ElseIf operandUnderlyingSpecialType = SpecialType.System_DateTime Then
helper = GetHelperForDateTimeBinaryOperation(opKind)
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
If helper IsNot Nothing Then
Debug.Assert(helper.MethodKind = MethodKind.Ordinary OrElse helper.MethodKind = MethodKind.UserDefinedOperator)
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, Me._factory.Literal(resultType.IsNullableType), _factory.MethodInfo(helper))
End If
' No helpers starting from here
Dim convertOperandsToInteger As Boolean = False
If operandUnderlyingSpecialType = SpecialType.System_Boolean Then
' For LT, LE, GT, and GE, if both the arguments are boolean arguments,
' we must generate a conversion from the boolean argument to an integer.
' Because True is -1, we need to switch the comparisons in these cases.
Select Case opKind
Case BinaryOperatorKind.LessThan
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.GreaterThan, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.LessThanOrEqual
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.GreaterThanOrEqual, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.GreaterThan
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.LessThan, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.GreaterThanOrEqual
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.LessThanOrEqual, isChecked)
convertOperandsToInteger = True
End Select
End If
Dim operandActiveType As TypeSymbol = operandType
' Convert arguments to underlying type if they are enums
If operandNotNullableType.IsEnumType AndAlso Not isIsIsNot Then
' Assuming both operands are of the same type
Dim newType As TypeSymbol = If(operandIsNullable, Me._factory.NullableOf(operandUnderlyingType), operandUnderlyingType)
left = CreateBuiltInConversion(operandActiveType, newType, left, node.Checked, False, ConversionSemantics.[Default])
right = CreateBuiltInConversion(operandActiveType, newType, right, node.Checked, False, ConversionSemantics.[Default])
operandActiveType = newType
End If
' Check if we need to convert the boolean arguments to Int32.
If convertOperandsToInteger AndAlso Not isIsIsNot Then
Dim newType As TypeSymbol = If(operandIsNullable, Me._factory.NullableOf(Me.Int32Type), Me.Int32Type)
left = Convert(left, newType, node.Checked)
right = Convert(right, newType, node.Checked)
operandActiveType = newType
End If
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, Me._factory.Literal(resultType.IsNullableType), Me._factory.Null)
End Function
#End Region
#Region "AndAlso, OrElse"
Private Function ConvertShortCircuitedBooleanOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultUnderlyingType As TypeSymbol = GetUnderlyingType(resultType)
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
Dim originalLeft As BoundExpression = node.Left
Dim left As BoundExpression = Visit(originalLeft)
Debug.Assert(TypeSymbol.Equals(resultType, originalLeft.Type, TypeCompareKind.ConsiderEverything))
Dim originalRight As BoundExpression = node.Right
Dim right As BoundExpression = Visit(originalRight)
Debug.Assert(TypeSymbol.Equals(resultType, originalRight.Type, TypeCompareKind.ConsiderEverything))
If resultUnderlyingType.IsObjectType Then
Dim systemBool As TypeSymbol = _factory.SpecialType(SpecialType.System_Boolean)
left = CreateBuiltInConversion(resultType, systemBool, left, node.Checked, False, ConversionSemantics.[Default])
right = CreateBuiltInConversion(resultType, systemBool, right, node.Checked, False, ConversionSemantics.[Default])
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
Dim result As BoundExpression = ConvertRuntimeHelperToExpressionTree(opMethod, left, right)
If resultUnderlyingType.IsObjectType Then
result = Convert(result, resultType, isChecked)
End If
Return result
End Function
#End Region
#Region "And, Or, Xor, ^, *, +, -, /, \, Mod, &, <<, >>"
Private Function ConvertBinaryOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultNotNullableType As TypeSymbol = resultType.GetNullableUnderlyingTypeOrSelf
Dim resultUnderlyingType As TypeSymbol = resultNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.And OrElse opKind = BinaryOperatorKind.Or OrElse opKind = BinaryOperatorKind.Xor OrElse
opKind = BinaryOperatorKind.Power OrElse opKind = BinaryOperatorKind.Multiply OrElse
opKind = BinaryOperatorKind.Add OrElse opKind = BinaryOperatorKind.Subtract OrElse
opKind = BinaryOperatorKind.Divide OrElse opKind = BinaryOperatorKind.IntegerDivide OrElse
opKind = BinaryOperatorKind.Modulo OrElse opKind = BinaryOperatorKind.Concatenate OrElse
opKind = BinaryOperatorKind.LeftShift OrElse opKind = BinaryOperatorKind.RightShift)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
' Do we need to use special helpers?
Dim helper As MethodSymbol = Nothing
If resultUnderlyingSpecialType = SpecialType.System_Object Then
helper = GetHelperForObjectBinaryOperation(opKind)
ElseIf resultUnderlyingSpecialType = SpecialType.System_Decimal Then
helper = GetHelperForDecimalBinaryOperation(opKind)
ElseIf opKind = BinaryOperatorKind.Concatenate Then
helper = DirectCast(_factory.SpecialMember(SpecialMember.System_String__ConcatStringString), MethodSymbol)
ElseIf opKind = BinaryOperatorKind.Power Then
helper = Me._factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Math__PowDoubleDouble)
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
Dim left As BoundExpression = Visit(node.Left)
Dim right As BoundExpression
If helper IsNot Nothing Then
right = Visit(node.Right)
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, _factory.MethodInfo(helper))
End If
' No special helper
Dim resultTypeIsNullable As Boolean = resultType.IsNullableType
Dim needToCastBackToByteOrSByte As Boolean = resultUnderlyingSpecialType = SpecialType.System_Byte OrElse
resultUnderlyingSpecialType = SpecialType.System_SByte
left = GenerateCastsForBinaryAndUnaryOperator(left,
resultTypeIsNullable,
resultNotNullableType,
isChecked AndAlso IsIntegralType(resultUnderlyingType),
needToCastBackToByteOrSByte)
If opKind = BinaryOperatorKind.LeftShift OrElse opKind = BinaryOperatorKind.RightShift Then
' Add mask for right operand of a shift operator.
right = MaskShiftCountOperand(node, resultType, isChecked)
isChecked = False ' final conversion shouldn't be checked for shift operands.
Else
right = Visit(node.Right)
right = GenerateCastsForBinaryAndUnaryOperator(right,
resultTypeIsNullable,
resultNotNullableType,
isChecked AndAlso IsIntegralType(resultUnderlyingType),
needToCastBackToByteOrSByte)
End If
Dim result As BoundExpression = ConvertRuntimeHelperToExpressionTree(opMethod, left, right)
If needToCastBackToByteOrSByte Then
Debug.Assert(resultUnderlyingSpecialType = SpecialType.System_Byte OrElse resultUnderlyingSpecialType = SpecialType.System_SByte)
result = Convert(result, If(resultTypeIsNullable, Me._factory.NullableOf(resultUnderlyingType), resultUnderlyingType), isChecked)
End If
If resultNotNullableType.IsEnumType Then
result = Convert(result, resultType, False)
End If
Return result
End Function
Private Function GenerateCastsForBinaryAndUnaryOperator(loweredOperand As BoundExpression,
isNullable As Boolean,
notNullableType As TypeSymbol,
checked As Boolean,
needToCastBackToByteOrSByte As Boolean) As BoundExpression
' Convert enums to their underlying types
If notNullableType.IsEnumType Then
Dim underlyingType As TypeSymbol = notNullableType.GetEnumUnderlyingTypeOrSelf
loweredOperand = Convert(loweredOperand, If(isNullable, Me._factory.NullableOf(underlyingType), underlyingType), False)
End If
' Byte and SByte promote operators to Int32, then demote after
If needToCastBackToByteOrSByte Then
loweredOperand = Convert(loweredOperand, If(isNullable, Me._factory.NullableOf(Me.Int32Type), Me.Int32Type), checked)
End If
Return loweredOperand
End Function
Private Function MaskShiftCountOperand(node As BoundBinaryOperator, resultType As TypeSymbol, isChecked As Boolean) As BoundExpression
Dim result As BoundExpression = Nothing
' NOTE: In case we have lifted binary operator, the original non-nullable right operand
' might be already converted to correspondent nullable type; we want to disregard
' such conversion before applying the mask and re-apply it after that
Dim applyConversionToNullable As Boolean = False
Dim originalRight As BoundExpression = node.Right
Debug.Assert(Not resultType.GetNullableUnderlyingTypeOrSelf().IsEnumType)
Dim shiftMask As Integer = CodeGen.CodeGenerator.GetShiftSizeMask(resultType.GetNullableUnderlyingTypeOrSelf())
Dim shiftedType As TypeSymbol = resultType
If resultType.IsNullableType AndAlso originalRight.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(originalRight, BoundConversion)
Dim operand As BoundExpression = conversion.Operand
Dim operandType As TypeSymbol = operand.Type
If ((conversion.ConversionKind And ConversionKind.Nullable) <> 0) AndAlso Not conversion.ExplicitCastInCode AndAlso Not operandType.IsNullableType Then
Debug.Assert(conversion.Type.IsNullableType AndAlso conversion.Type.GetNullableUnderlyingType.SpecialType = SpecialType.System_Int32)
' type of the right operand before conversion
shiftedType = operandType.GetEnumUnderlyingTypeOrSelf()
' visit and convert operand
result = Visit(operand)
If Not TypeSymbol.Equals(operandType, Me.Int32Type, TypeCompareKind.ConsiderEverything) Then
result = CreateBuiltInConversion(operandType, Me.Int32Type, result, isChecked, False, ConversionSemantics.[Default])
End If
applyConversionToNullable = True
End If
End If
If Not applyConversionToNullable Then
result = Visit(originalRight)
End If
' Add mask for right operand of a shift operator.
result = MaskShiftCountOperand(result, shiftedType, shiftMask, result.ConstantValueOpt, isChecked)
If applyConversionToNullable Then
result = Convert(result, Me._factory.NullableOf(Me.Int32Type), isChecked)
End If
Return result
End Function
''' <summary>
''' The shift count for a left-shift or right-shift operator needs to be masked according to the type
''' of the left hand side, unless the shift count is an in-range constant. This is similar to what is
''' done in code gen.
''' </summary>
Private Function MaskShiftCountOperand(loweredOperand As BoundExpression, shiftedType As TypeSymbol, shiftMask As Integer, shiftConst As ConstantValue, isChecked As Boolean) As BoundExpression
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMask Then
Dim constantOperand As BoundExpression =
ConvertRuntimeHelperToExpressionTree("Constant",
Me._factory.Convert(Me.ObjectType, Me._factory.Literal(shiftMask)),
Me._factory.Typeof(Me.Int32Type))
Dim isNullable As Boolean = shiftedType.IsNullableType
Dim isInt32 As Boolean = shiftedType.GetNullableUnderlyingTypeOrSelf.SpecialType = SpecialType.System_Int32
Dim int32Nullable As TypeSymbol = If(isNullable, Me._factory.NullableOf(Me.Int32Type), Nothing)
If isNullable Then
constantOperand = Convert(constantOperand, int32Nullable, isChecked)
End If
loweredOperand = ConvertRuntimeHelperToExpressionTree("And", loweredOperand, constantOperand)
End If
Return loweredOperand
End Function
#End Region
#Region "Utility"
Private Function GetHelperForDecimalBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim specialHelper As SpecialMember
Select Case opKind
Case BinaryOperatorKind.Add
specialHelper = SpecialMember.System_Decimal__AddDecimalDecimal
Case BinaryOperatorKind.Subtract
specialHelper = SpecialMember.System_Decimal__SubtractDecimalDecimal
Case BinaryOperatorKind.Multiply
specialHelper = SpecialMember.System_Decimal__MultiplyDecimalDecimal
Case BinaryOperatorKind.Divide
specialHelper = SpecialMember.System_Decimal__DivideDecimalDecimal
Case BinaryOperatorKind.Modulo
specialHelper = SpecialMember.System_Decimal__ModuloDecimalDecimal
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.Is
specialHelper = SpecialMember.System_Decimal__op_Equality
Case BinaryOperatorKind.NotEquals,
BinaryOperatorKind.IsNot
specialHelper = SpecialMember.System_Decimal__op_Inequality
Case BinaryOperatorKind.LessThan
specialHelper = SpecialMember.System_Decimal__op_LessThan
Case BinaryOperatorKind.LessThanOrEqual
specialHelper = SpecialMember.System_Decimal__op_LessThanOrEqual
Case BinaryOperatorKind.GreaterThan
specialHelper = SpecialMember.System_Decimal__op_GreaterThan
Case BinaryOperatorKind.GreaterThanOrEqual
specialHelper = SpecialMember.System_Decimal__op_GreaterThanOrEqual
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return DirectCast(_factory.SpecialMember(specialHelper), MethodSymbol)
End Function
Private Function GetHelperForDateTimeBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim specialHelper As SpecialMember
Select Case opKind
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.Is
specialHelper = SpecialMember.System_DateTime__op_Equality
Case BinaryOperatorKind.NotEquals,
BinaryOperatorKind.IsNot
specialHelper = SpecialMember.System_DateTime__op_Inequality
Case BinaryOperatorKind.LessThan
specialHelper = SpecialMember.System_DateTime__op_LessThan
Case BinaryOperatorKind.LessThanOrEqual
specialHelper = SpecialMember.System_DateTime__op_LessThanOrEqual
Case BinaryOperatorKind.GreaterThan
specialHelper = SpecialMember.System_DateTime__op_GreaterThan
Case BinaryOperatorKind.GreaterThanOrEqual
specialHelper = SpecialMember.System_DateTime__op_GreaterThanOrEqual
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return DirectCast(_factory.SpecialMember(specialHelper), MethodSymbol)
End Function
Private Function GetHelperForObjectBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim wellKnownHelper As WellKnownMember
Select Case opKind
Case BinaryOperatorKind.Add
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject
Case BinaryOperatorKind.Subtract
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject
Case BinaryOperatorKind.Multiply
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject
Case BinaryOperatorKind.Divide
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject
Case BinaryOperatorKind.IntegerDivide
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject
Case BinaryOperatorKind.Modulo
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject
Case BinaryOperatorKind.Power
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject
Case BinaryOperatorKind.And
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject
Case BinaryOperatorKind.Xor
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject
Case BinaryOperatorKind.Or
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject
Case BinaryOperatorKind.LeftShift
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject
Case BinaryOperatorKind.RightShift
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject
Case BinaryOperatorKind.Concatenate
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return Me._factory.WellKnownMember(Of MethodSymbol)(wellKnownHelper)
End Function
Private Shared Function GetBinaryOperatorMethodName(opKind As BinaryOperatorKind, isChecked As Boolean) As String
Select Case (opKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.Add
Return If(isChecked, "AddChecked", "Add")
Case BinaryOperatorKind.Subtract
Return If(isChecked, "SubtractChecked", "Subtract")
Case BinaryOperatorKind.Multiply
Return If(isChecked, "MultiplyChecked", "Multiply")
Case BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.Divide
Return "Divide"
Case BinaryOperatorKind.Modulo
Return "Modulo"
Case BinaryOperatorKind.Power
Return "Power"
Case BinaryOperatorKind.And
Return "And"
Case BinaryOperatorKind.Or
Return "Or"
Case BinaryOperatorKind.Xor
Return "ExclusiveOr"
Case BinaryOperatorKind.LeftShift
Return "LeftShift"
Case BinaryOperatorKind.RightShift
Return "RightShift"
Case BinaryOperatorKind.Is,
BinaryOperatorKind.Equals
Return "Equal"
Case BinaryOperatorKind.IsNot,
BinaryOperatorKind.NotEquals
Return "NotEqual"
Case BinaryOperatorKind.LessThan
Return "LessThan"
Case BinaryOperatorKind.LessThanOrEqual
Return "LessThanOrEqual"
Case BinaryOperatorKind.GreaterThan
Return "GreaterThan"
Case BinaryOperatorKind.GreaterThanOrEqual
Return "GreaterThanOrEqual"
Case BinaryOperatorKind.AndAlso
Return "AndAlso"
Case BinaryOperatorKind.OrElse
Return "OrElse"
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
End Function
Private Shared Function AdjustCallArgumentForLiftedOperator(oldArg As BoundExpression, parameterType As TypeSymbol) As BoundExpression
Debug.Assert(oldArg.Type.IsNullableType)
Debug.Assert(Not parameterType.IsNullableType)
Debug.Assert(TypeSymbol.Equals(oldArg.Type.GetNullableUnderlyingTypeOrSelf(), parameterType, TypeCompareKind.ConsiderEverything))
If oldArg.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(oldArg, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
If objCreation.Arguments.Length = 1 Then
Return objCreation.Arguments(0)
End If
End If
' Else just wrap in conversion
Return New BoundConversion(oldArg.Syntax, oldArg, ConversionKind.NarrowingNullable, False, False, parameterType)
End Function
Private Function AdjustCallForLiftedOperator(opKind As BinaryOperatorKind, [call] As BoundCall, resultType As TypeSymbol) As BoundExpression
Debug.Assert((opKind And BinaryOperatorKind.Lifted) <> 0)
Debug.Assert((opKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Like OrElse
(opKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Concatenate)
Return AdjustCallForLiftedOperator_DoNotCallDirectly([call], resultType)
End Function
Private Function AdjustCallForLiftedOperator(opKind As UnaryOperatorKind, [call] As BoundCall, resultType As TypeSymbol) As BoundExpression
Debug.Assert((opKind And UnaryOperatorKind.Lifted) <> 0)
Debug.Assert((opKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.IsTrue OrElse
(opKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.IsFalse)
Return AdjustCallForLiftedOperator_DoNotCallDirectly([call], resultType)
End Function
Private Function AdjustCallForLiftedOperator_DoNotCallDirectly([call] As BoundCall, resultType As TypeSymbol) As BoundExpression
' NOTE: those operators which are not converted into a special factory methods, but rather
' into a direct call we need to adjust the type of operands and the resulting type to
' that of the method. This method is only to be called for particular operators!!!!
Dim parameters As ImmutableArray(Of ParameterSymbol) = [call].Method.Parameters
Debug.Assert(parameters.Length > 0)
Dim oldArgs As ImmutableArray(Of BoundExpression) = [call].Arguments
Debug.Assert(parameters.Length = oldArgs.Length)
Dim newArgs(oldArgs.Length - 1) As BoundExpression
For i = 0 To oldArgs.Length - 1
newArgs(i) = AdjustCallArgumentForLiftedOperator(oldArgs(i), parameters(i).Type)
Next
Dim methodReturnType As TypeSymbol = [call].Method.ReturnType
Debug.Assert(resultType.GetNullableUnderlyingTypeOrSelf().
IsSameTypeIgnoringAll(methodReturnType.GetNullableUnderlyingTypeOrSelf))
[call] = [call].Update([call].Method,
[call].MethodGroupOpt,
[call].ReceiverOpt,
newArgs.AsImmutableOrNull,
[call].DefaultArguments,
[call].ConstantValueOpt,
isLValue:=[call].IsLValue,
suppressObjectClone:=[call].SuppressObjectClone,
type:=methodReturnType)
If resultType.IsNullableType <> methodReturnType.IsNullableType Then
Return Me._factory.Convert(resultType, [call])
End If
Return [call]
End Function
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class ExpressionLambdaRewriter
Private Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundExpression
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
Select Case node.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.And,
BinaryOperatorKind.Or,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Power,
BinaryOperatorKind.Multiply,
BinaryOperatorKind.Add,
BinaryOperatorKind.Subtract,
BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.Concatenate,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift
Return ConvertBinaryOperator(node)
Case BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan
Return ConvertBooleanOperator(node)
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso
Return ConvertShortCircuitedBooleanOperator(node)
Case BinaryOperatorKind.Like
' Like operator should already be rewritten by this time
Throw ExceptionUtilities.UnexpectedValue(node.OperatorKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.OperatorKind)
End Select
End Function
Private Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundExpression
Dim opKind As BinaryOperatorKind = node.OperatorKind And BinaryOperatorKind.OpMask
Dim isLifted As Boolean = (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(node.Call.Method.ReturnType)
Select Case opKind
Case BinaryOperatorKind.Like,
BinaryOperatorKind.Concatenate
Return ConvertUserDefinedLikeOrConcate(node)
Case BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan
' Error should have been reported by DiagnosticsPass, see
' DiagnosticsPass.VisitUserDefinedBinaryOperator
Debug.Assert(Not isLifted OrElse Not node.Call.Method.ReturnType.IsNullableType)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, isChecked),
Visit(node.Left), Visit(node.Right),
Me._factory.Literal(isLifted),
_factory.MethodInfo(node.Call.Method))
Case Else
' Error should have been reported by DiagnosticsPass, see
' DiagnosticsPass.VisitUserDefinedBinaryOperator
Debug.Assert(Not isLifted OrElse Not node.Call.Method.ReturnType.IsNullableType)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, isChecked),
Visit(node.Left), Visit(node.Right),
_factory.MethodInfo(node.Call.Method))
End Select
End Function
Private Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundExpression
Dim operand As BoundUserDefinedBinaryOperator = node.BitwiseOperator
Dim opKind As BinaryOperatorKind = operand.OperatorKind And BinaryOperatorKind.OpMask
' See comment in DiagnosticsPass.VisitUserDefinedShortCircuitingOperator
Debug.Assert(operand.Call.Method.ReturnType.IsSameTypeIgnoringAll(operand.Call.Method.Parameters(0).Type) AndAlso
operand.Call.Method.ReturnType.IsSameTypeIgnoringAll(operand.Call.Method.Parameters(1).Type))
opKind = If(opKind = BinaryOperatorKind.And, BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse)
Return ConvertRuntimeHelperToExpressionTree(GetBinaryOperatorMethodName(opKind, False),
Visit(operand.Left), Visit(operand.Right),
_factory.MethodInfo(operand.Call.Method))
End Function
#Region "User Defined Like"
Private Function ConvertUserDefinedLikeOrConcate(node As BoundUserDefinedBinaryOperator) As BoundExpression
Dim [call] As BoundCall = node.Call
Dim opKind As BinaryOperatorKind = node.OperatorKind
If (opKind And BinaryOperatorKind.Lifted) = 0 Then
Return VisitInternal([call])
End If
Return VisitInternal(AdjustCallForLiftedOperator(opKind, [call], node.Type))
End Function
#End Region
#Region "Is, IsNot, <, <=, >=, >"
Private Function ConvertBooleanOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultNotNullableType As TypeSymbol = resultType.GetNullableUnderlyingTypeOrSelf
Dim resultUnderlyingType As TypeSymbol = resultNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot OrElse
opKind = BinaryOperatorKind.Equals OrElse opKind = BinaryOperatorKind.NotEquals OrElse
opKind = BinaryOperatorKind.LessThan OrElse opKind = BinaryOperatorKind.GreaterThan OrElse
opKind = BinaryOperatorKind.LessThanOrEqual OrElse opKind = BinaryOperatorKind.GreaterThanOrEqual)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
' Prepare left and right
Dim originalLeft As BoundExpression = node.Left
Dim operandType As TypeSymbol = originalLeft.Type
Dim left As BoundExpression = Nothing
Dim originalRight As BoundExpression = node.Right
Dim right As BoundExpression = Nothing
Dim isIsIsNot As Boolean = (opKind = BinaryOperatorKind.Is) OrElse (opKind = BinaryOperatorKind.IsNot)
If isIsIsNot Then
' Ensure Nothing literals is converted to the type of an opposite operand
If originalLeft.IsNothingLiteral Then
If originalRight.Type.IsNullableType Then
Debug.Assert(originalLeft.Type Is Nothing OrElse originalLeft.Type.IsObjectType)
left = CreateLiteralExpression(originalLeft, originalRight.Type)
operandType = originalRight.Type
End If
ElseIf originalRight.IsNothingLiteral Then
If originalLeft.Type.IsNullableType Then
Debug.Assert(originalRight.Type Is Nothing OrElse originalRight.Type.IsObjectType)
right = CreateLiteralExpression(originalRight, originalLeft.Type)
End If
End If
End If
Dim operandIsNullable As Boolean = operandType.IsNullableType
Dim operandNotNullableType As TypeSymbol = operandType.GetNullableUnderlyingTypeOrSelf
Dim operandUnderlyingType As TypeSymbol = operandNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim operandUnderlyingSpecialType As SpecialType = operandUnderlyingType.SpecialType
If left Is Nothing Then
left = Visit(originalLeft)
Debug.Assert(TypeSymbol.Equals(operandType, originalLeft.Type, TypeCompareKind.ConsiderEverything))
End If
If right Is Nothing Then
right = Visit(originalRight)
Debug.Assert(TypeSymbol.Equals(operandType, originalRight.Type, TypeCompareKind.ConsiderEverything))
End If
' Do we need to handle special cases?
Dim helper As MethodSymbol = Nothing
' [>|>=|<|<=] with System.Object argument should already be rewritten into proper calls
Debug.Assert(operandUnderlyingSpecialType <> SpecialType.System_Object OrElse isIsIsNot)
' All boolean operators with System.String argument should already be rewritten into proper calls
Debug.Assert(operandUnderlyingSpecialType <> SpecialType.System_String)
If operandUnderlyingSpecialType = SpecialType.System_Decimal Then
helper = GetHelperForDecimalBinaryOperation(opKind)
ElseIf operandUnderlyingSpecialType = SpecialType.System_DateTime Then
helper = GetHelperForDateTimeBinaryOperation(opKind)
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
If helper IsNot Nothing Then
Debug.Assert(helper.MethodKind = MethodKind.Ordinary OrElse helper.MethodKind = MethodKind.UserDefinedOperator)
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, Me._factory.Literal(resultType.IsNullableType), _factory.MethodInfo(helper))
End If
' No helpers starting from here
Dim convertOperandsToInteger As Boolean = False
If operandUnderlyingSpecialType = SpecialType.System_Boolean Then
' For LT, LE, GT, and GE, if both the arguments are boolean arguments,
' we must generate a conversion from the boolean argument to an integer.
' Because True is -1, we need to switch the comparisons in these cases.
Select Case opKind
Case BinaryOperatorKind.LessThan
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.GreaterThan, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.LessThanOrEqual
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.GreaterThanOrEqual, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.GreaterThan
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.LessThan, isChecked)
convertOperandsToInteger = True
Case BinaryOperatorKind.GreaterThanOrEqual
opMethod = GetBinaryOperatorMethodName(BinaryOperatorKind.LessThanOrEqual, isChecked)
convertOperandsToInteger = True
End Select
End If
Dim operandActiveType As TypeSymbol = operandType
' Convert arguments to underlying type if they are enums
If operandNotNullableType.IsEnumType AndAlso Not isIsIsNot Then
' Assuming both operands are of the same type
Dim newType As TypeSymbol = If(operandIsNullable, Me._factory.NullableOf(operandUnderlyingType), operandUnderlyingType)
left = CreateBuiltInConversion(operandActiveType, newType, left, node.Checked, False, ConversionSemantics.[Default])
right = CreateBuiltInConversion(operandActiveType, newType, right, node.Checked, False, ConversionSemantics.[Default])
operandActiveType = newType
End If
' Check if we need to convert the boolean arguments to Int32.
If convertOperandsToInteger AndAlso Not isIsIsNot Then
Dim newType As TypeSymbol = If(operandIsNullable, Me._factory.NullableOf(Me.Int32Type), Me.Int32Type)
left = Convert(left, newType, node.Checked)
right = Convert(right, newType, node.Checked)
operandActiveType = newType
End If
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, Me._factory.Literal(resultType.IsNullableType), Me._factory.Null)
End Function
#End Region
#Region "AndAlso, OrElse"
Private Function ConvertShortCircuitedBooleanOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultUnderlyingType As TypeSymbol = GetUnderlyingType(resultType)
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
Dim originalLeft As BoundExpression = node.Left
Dim left As BoundExpression = Visit(originalLeft)
Debug.Assert(TypeSymbol.Equals(resultType, originalLeft.Type, TypeCompareKind.ConsiderEverything))
Dim originalRight As BoundExpression = node.Right
Dim right As BoundExpression = Visit(originalRight)
Debug.Assert(TypeSymbol.Equals(resultType, originalRight.Type, TypeCompareKind.ConsiderEverything))
If resultUnderlyingType.IsObjectType Then
Dim systemBool As TypeSymbol = _factory.SpecialType(SpecialType.System_Boolean)
left = CreateBuiltInConversion(resultType, systemBool, left, node.Checked, False, ConversionSemantics.[Default])
right = CreateBuiltInConversion(resultType, systemBool, right, node.Checked, False, ConversionSemantics.[Default])
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
Dim result As BoundExpression = ConvertRuntimeHelperToExpressionTree(opMethod, left, right)
If resultUnderlyingType.IsObjectType Then
result = Convert(result, resultType, isChecked)
End If
Return result
End Function
#End Region
#Region "And, Or, Xor, ^, *, +, -, /, \, Mod, &, <<, >>"
Private Function ConvertBinaryOperator(node As BoundBinaryOperator) As BoundExpression
Dim resultType As TypeSymbol = node.Type
Dim resultNotNullableType As TypeSymbol = resultType.GetNullableUnderlyingTypeOrSelf
Dim resultUnderlyingType As TypeSymbol = resultNotNullableType.GetEnumUnderlyingTypeOrSelf
Dim resultUnderlyingSpecialType As SpecialType = resultUnderlyingType.SpecialType
Dim opKind = node.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.And OrElse opKind = BinaryOperatorKind.Or OrElse opKind = BinaryOperatorKind.Xor OrElse
opKind = BinaryOperatorKind.Power OrElse opKind = BinaryOperatorKind.Multiply OrElse
opKind = BinaryOperatorKind.Add OrElse opKind = BinaryOperatorKind.Subtract OrElse
opKind = BinaryOperatorKind.Divide OrElse opKind = BinaryOperatorKind.IntegerDivide OrElse
opKind = BinaryOperatorKind.Modulo OrElse opKind = BinaryOperatorKind.Concatenate OrElse
opKind = BinaryOperatorKind.LeftShift OrElse opKind = BinaryOperatorKind.RightShift)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.UserDefined) = 0)
' Do we need to use special helpers?
Dim helper As MethodSymbol = Nothing
If resultUnderlyingSpecialType = SpecialType.System_Object Then
helper = GetHelperForObjectBinaryOperation(opKind)
ElseIf resultUnderlyingSpecialType = SpecialType.System_Decimal Then
helper = GetHelperForDecimalBinaryOperation(opKind)
ElseIf opKind = BinaryOperatorKind.Concatenate Then
helper = DirectCast(_factory.SpecialMember(SpecialMember.System_String__ConcatStringString), MethodSymbol)
ElseIf opKind = BinaryOperatorKind.Power Then
helper = Me._factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Math__PowDoubleDouble)
End If
Dim isChecked As Boolean = node.Checked AndAlso IsIntegralType(resultUnderlyingType)
Dim opMethod As String = GetBinaryOperatorMethodName(opKind, isChecked)
Dim left As BoundExpression = Visit(node.Left)
Dim right As BoundExpression
If helper IsNot Nothing Then
right = Visit(node.Right)
Return ConvertRuntimeHelperToExpressionTree(opMethod, left, right, _factory.MethodInfo(helper))
End If
' No special helper
Dim resultTypeIsNullable As Boolean = resultType.IsNullableType
Dim needToCastBackToByteOrSByte As Boolean = resultUnderlyingSpecialType = SpecialType.System_Byte OrElse
resultUnderlyingSpecialType = SpecialType.System_SByte
left = GenerateCastsForBinaryAndUnaryOperator(left,
resultTypeIsNullable,
resultNotNullableType,
isChecked AndAlso IsIntegralType(resultUnderlyingType),
needToCastBackToByteOrSByte)
If opKind = BinaryOperatorKind.LeftShift OrElse opKind = BinaryOperatorKind.RightShift Then
' Add mask for right operand of a shift operator.
right = MaskShiftCountOperand(node, resultType, isChecked)
isChecked = False ' final conversion shouldn't be checked for shift operands.
Else
right = Visit(node.Right)
right = GenerateCastsForBinaryAndUnaryOperator(right,
resultTypeIsNullable,
resultNotNullableType,
isChecked AndAlso IsIntegralType(resultUnderlyingType),
needToCastBackToByteOrSByte)
End If
Dim result As BoundExpression = ConvertRuntimeHelperToExpressionTree(opMethod, left, right)
If needToCastBackToByteOrSByte Then
Debug.Assert(resultUnderlyingSpecialType = SpecialType.System_Byte OrElse resultUnderlyingSpecialType = SpecialType.System_SByte)
result = Convert(result, If(resultTypeIsNullable, Me._factory.NullableOf(resultUnderlyingType), resultUnderlyingType), isChecked)
End If
If resultNotNullableType.IsEnumType Then
result = Convert(result, resultType, False)
End If
Return result
End Function
Private Function GenerateCastsForBinaryAndUnaryOperator(loweredOperand As BoundExpression,
isNullable As Boolean,
notNullableType As TypeSymbol,
checked As Boolean,
needToCastBackToByteOrSByte As Boolean) As BoundExpression
' Convert enums to their underlying types
If notNullableType.IsEnumType Then
Dim underlyingType As TypeSymbol = notNullableType.GetEnumUnderlyingTypeOrSelf
loweredOperand = Convert(loweredOperand, If(isNullable, Me._factory.NullableOf(underlyingType), underlyingType), False)
End If
' Byte and SByte promote operators to Int32, then demote after
If needToCastBackToByteOrSByte Then
loweredOperand = Convert(loweredOperand, If(isNullable, Me._factory.NullableOf(Me.Int32Type), Me.Int32Type), checked)
End If
Return loweredOperand
End Function
Private Function MaskShiftCountOperand(node As BoundBinaryOperator, resultType As TypeSymbol, isChecked As Boolean) As BoundExpression
Dim result As BoundExpression = Nothing
' NOTE: In case we have lifted binary operator, the original non-nullable right operand
' might be already converted to correspondent nullable type; we want to disregard
' such conversion before applying the mask and re-apply it after that
Dim applyConversionToNullable As Boolean = False
Dim originalRight As BoundExpression = node.Right
Debug.Assert(Not resultType.GetNullableUnderlyingTypeOrSelf().IsEnumType)
Dim shiftMask As Integer = CodeGen.CodeGenerator.GetShiftSizeMask(resultType.GetNullableUnderlyingTypeOrSelf())
Dim shiftedType As TypeSymbol = resultType
If resultType.IsNullableType AndAlso originalRight.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(originalRight, BoundConversion)
Dim operand As BoundExpression = conversion.Operand
Dim operandType As TypeSymbol = operand.Type
If ((conversion.ConversionKind And ConversionKind.Nullable) <> 0) AndAlso Not conversion.ExplicitCastInCode AndAlso Not operandType.IsNullableType Then
Debug.Assert(conversion.Type.IsNullableType AndAlso conversion.Type.GetNullableUnderlyingType.SpecialType = SpecialType.System_Int32)
' type of the right operand before conversion
shiftedType = operandType.GetEnumUnderlyingTypeOrSelf()
' visit and convert operand
result = Visit(operand)
If Not TypeSymbol.Equals(operandType, Me.Int32Type, TypeCompareKind.ConsiderEverything) Then
result = CreateBuiltInConversion(operandType, Me.Int32Type, result, isChecked, False, ConversionSemantics.[Default])
End If
applyConversionToNullable = True
End If
End If
If Not applyConversionToNullable Then
result = Visit(originalRight)
End If
' Add mask for right operand of a shift operator.
result = MaskShiftCountOperand(result, shiftedType, shiftMask, result.ConstantValueOpt, isChecked)
If applyConversionToNullable Then
result = Convert(result, Me._factory.NullableOf(Me.Int32Type), isChecked)
End If
Return result
End Function
''' <summary>
''' The shift count for a left-shift or right-shift operator needs to be masked according to the type
''' of the left hand side, unless the shift count is an in-range constant. This is similar to what is
''' done in code gen.
''' </summary>
Private Function MaskShiftCountOperand(loweredOperand As BoundExpression, shiftedType As TypeSymbol, shiftMask As Integer, shiftConst As ConstantValue, isChecked As Boolean) As BoundExpression
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMask Then
Dim constantOperand As BoundExpression =
ConvertRuntimeHelperToExpressionTree("Constant",
Me._factory.Convert(Me.ObjectType, Me._factory.Literal(shiftMask)),
Me._factory.Typeof(Me.Int32Type))
Dim isNullable As Boolean = shiftedType.IsNullableType
Dim isInt32 As Boolean = shiftedType.GetNullableUnderlyingTypeOrSelf.SpecialType = SpecialType.System_Int32
Dim int32Nullable As TypeSymbol = If(isNullable, Me._factory.NullableOf(Me.Int32Type), Nothing)
If isNullable Then
constantOperand = Convert(constantOperand, int32Nullable, isChecked)
End If
loweredOperand = ConvertRuntimeHelperToExpressionTree("And", loweredOperand, constantOperand)
End If
Return loweredOperand
End Function
#End Region
#Region "Utility"
Private Function GetHelperForDecimalBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim specialHelper As SpecialMember
Select Case opKind
Case BinaryOperatorKind.Add
specialHelper = SpecialMember.System_Decimal__AddDecimalDecimal
Case BinaryOperatorKind.Subtract
specialHelper = SpecialMember.System_Decimal__SubtractDecimalDecimal
Case BinaryOperatorKind.Multiply
specialHelper = SpecialMember.System_Decimal__MultiplyDecimalDecimal
Case BinaryOperatorKind.Divide
specialHelper = SpecialMember.System_Decimal__DivideDecimalDecimal
Case BinaryOperatorKind.Modulo
specialHelper = SpecialMember.System_Decimal__ModuloDecimalDecimal
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.Is
specialHelper = SpecialMember.System_Decimal__op_Equality
Case BinaryOperatorKind.NotEquals,
BinaryOperatorKind.IsNot
specialHelper = SpecialMember.System_Decimal__op_Inequality
Case BinaryOperatorKind.LessThan
specialHelper = SpecialMember.System_Decimal__op_LessThan
Case BinaryOperatorKind.LessThanOrEqual
specialHelper = SpecialMember.System_Decimal__op_LessThanOrEqual
Case BinaryOperatorKind.GreaterThan
specialHelper = SpecialMember.System_Decimal__op_GreaterThan
Case BinaryOperatorKind.GreaterThanOrEqual
specialHelper = SpecialMember.System_Decimal__op_GreaterThanOrEqual
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return DirectCast(_factory.SpecialMember(specialHelper), MethodSymbol)
End Function
Private Function GetHelperForDateTimeBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim specialHelper As SpecialMember
Select Case opKind
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.Is
specialHelper = SpecialMember.System_DateTime__op_Equality
Case BinaryOperatorKind.NotEquals,
BinaryOperatorKind.IsNot
specialHelper = SpecialMember.System_DateTime__op_Inequality
Case BinaryOperatorKind.LessThan
specialHelper = SpecialMember.System_DateTime__op_LessThan
Case BinaryOperatorKind.LessThanOrEqual
specialHelper = SpecialMember.System_DateTime__op_LessThanOrEqual
Case BinaryOperatorKind.GreaterThan
specialHelper = SpecialMember.System_DateTime__op_GreaterThan
Case BinaryOperatorKind.GreaterThanOrEqual
specialHelper = SpecialMember.System_DateTime__op_GreaterThanOrEqual
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return DirectCast(_factory.SpecialMember(specialHelper), MethodSymbol)
End Function
Private Function GetHelperForObjectBinaryOperation(opKind As BinaryOperatorKind) As MethodSymbol
opKind = opKind And BinaryOperatorKind.OpMask
Dim wellKnownHelper As WellKnownMember
Select Case opKind
Case BinaryOperatorKind.Add
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject
Case BinaryOperatorKind.Subtract
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject
Case BinaryOperatorKind.Multiply
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject
Case BinaryOperatorKind.Divide
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject
Case BinaryOperatorKind.IntegerDivide
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject
Case BinaryOperatorKind.Modulo
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject
Case BinaryOperatorKind.Power
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject
Case BinaryOperatorKind.And
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject
Case BinaryOperatorKind.Xor
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject
Case BinaryOperatorKind.Or
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject
Case BinaryOperatorKind.LeftShift
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject
Case BinaryOperatorKind.RightShift
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject
Case BinaryOperatorKind.Concatenate
wellKnownHelper = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
Return Me._factory.WellKnownMember(Of MethodSymbol)(wellKnownHelper)
End Function
Private Shared Function GetBinaryOperatorMethodName(opKind As BinaryOperatorKind, isChecked As Boolean) As String
Select Case (opKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.Add
Return If(isChecked, "AddChecked", "Add")
Case BinaryOperatorKind.Subtract
Return If(isChecked, "SubtractChecked", "Subtract")
Case BinaryOperatorKind.Multiply
Return If(isChecked, "MultiplyChecked", "Multiply")
Case BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.Divide
Return "Divide"
Case BinaryOperatorKind.Modulo
Return "Modulo"
Case BinaryOperatorKind.Power
Return "Power"
Case BinaryOperatorKind.And
Return "And"
Case BinaryOperatorKind.Or
Return "Or"
Case BinaryOperatorKind.Xor
Return "ExclusiveOr"
Case BinaryOperatorKind.LeftShift
Return "LeftShift"
Case BinaryOperatorKind.RightShift
Return "RightShift"
Case BinaryOperatorKind.Is,
BinaryOperatorKind.Equals
Return "Equal"
Case BinaryOperatorKind.IsNot,
BinaryOperatorKind.NotEquals
Return "NotEqual"
Case BinaryOperatorKind.LessThan
Return "LessThan"
Case BinaryOperatorKind.LessThanOrEqual
Return "LessThanOrEqual"
Case BinaryOperatorKind.GreaterThan
Return "GreaterThan"
Case BinaryOperatorKind.GreaterThanOrEqual
Return "GreaterThanOrEqual"
Case BinaryOperatorKind.AndAlso
Return "AndAlso"
Case BinaryOperatorKind.OrElse
Return "OrElse"
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
End Function
Private Shared Function AdjustCallArgumentForLiftedOperator(oldArg As BoundExpression, parameterType As TypeSymbol) As BoundExpression
Debug.Assert(oldArg.Type.IsNullableType)
Debug.Assert(Not parameterType.IsNullableType)
Debug.Assert(TypeSymbol.Equals(oldArg.Type.GetNullableUnderlyingTypeOrSelf(), parameterType, TypeCompareKind.ConsiderEverything))
If oldArg.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(oldArg, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
If objCreation.Arguments.Length = 1 Then
Return objCreation.Arguments(0)
End If
End If
' Else just wrap in conversion
Return New BoundConversion(oldArg.Syntax, oldArg, ConversionKind.NarrowingNullable, False, False, parameterType)
End Function
Private Function AdjustCallForLiftedOperator(opKind As BinaryOperatorKind, [call] As BoundCall, resultType As TypeSymbol) As BoundExpression
Debug.Assert((opKind And BinaryOperatorKind.Lifted) <> 0)
Debug.Assert((opKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Like OrElse
(opKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Concatenate)
Return AdjustCallForLiftedOperator_DoNotCallDirectly([call], resultType)
End Function
Private Function AdjustCallForLiftedOperator(opKind As UnaryOperatorKind, [call] As BoundCall, resultType As TypeSymbol) As BoundExpression
Debug.Assert((opKind And UnaryOperatorKind.Lifted) <> 0)
Debug.Assert((opKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.IsTrue OrElse
(opKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.IsFalse)
Return AdjustCallForLiftedOperator_DoNotCallDirectly([call], resultType)
End Function
Private Function AdjustCallForLiftedOperator_DoNotCallDirectly([call] As BoundCall, resultType As TypeSymbol) As BoundExpression
' NOTE: those operators which are not converted into a special factory methods, but rather
' into a direct call we need to adjust the type of operands and the resulting type to
' that of the method. This method is only to be called for particular operators!!!!
Dim parameters As ImmutableArray(Of ParameterSymbol) = [call].Method.Parameters
Debug.Assert(parameters.Length > 0)
Dim oldArgs As ImmutableArray(Of BoundExpression) = [call].Arguments
Debug.Assert(parameters.Length = oldArgs.Length)
Dim newArgs(oldArgs.Length - 1) As BoundExpression
For i = 0 To oldArgs.Length - 1
newArgs(i) = AdjustCallArgumentForLiftedOperator(oldArgs(i), parameters(i).Type)
Next
Dim methodReturnType As TypeSymbol = [call].Method.ReturnType
Debug.Assert(resultType.GetNullableUnderlyingTypeOrSelf().
IsSameTypeIgnoringAll(methodReturnType.GetNullableUnderlyingTypeOrSelf))
[call] = [call].Update([call].Method,
[call].MethodGroupOpt,
[call].ReceiverOpt,
newArgs.AsImmutableOrNull,
[call].DefaultArguments,
[call].ConstantValueOpt,
isLValue:=[call].IsLValue,
suppressObjectClone:=[call].SuppressObjectClone,
type:=methodReturnType)
If resultType.IsNullableType <> methodReturnType.IsNullableType Then
Return Me._factory.Convert(resultType, [call])
End If
Return [call]
End Function
#End Region
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
#endif
namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InlineDeclaration), Shared]
internal partial class CSharpInlineDeclarationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpInlineDeclarationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.InlineDeclarationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
// Gather all statements to be removed
// We need this to find the statements we can safely attach trivia to
var declarationsToRemove = new HashSet<StatementSyntax>();
foreach (var diagnostic in diagnostics)
{
declarationsToRemove.Add((LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken).Parent.Parent);
}
// Attempt to use an out-var declaration if that's the style the user prefers.
// Note: if using 'var' would cause a problem, we will use the actual type
// of the local. This is necessary in some cases (for example, when the
// type of the out-var-decl affects overload resolution or generic instantiation).
var originalRoot = editor.OriginalRoot;
var originalNodes = diagnostics.SelectAsArray(diagnostic => FindDiagnosticNodes(diagnostic, cancellationToken));
await editor.ApplyExpressionLevelSemanticEditsAsync(
document,
originalNodes,
t =>
{
using var additionalNodesToTrackDisposer = ArrayBuilder<SyntaxNode>.GetInstance(capacity: 2, out var additionalNodesToTrack);
additionalNodesToTrack.Add(t.identifier);
additionalNodesToTrack.Add(t.declarator);
return (t.invocationOrCreation, additionalNodesToTrack.ToImmutable());
},
(_1, _2, _3) => true,
(semanticModel, currentRoot, t, currentNode)
=> ReplaceIdentifierWithInlineDeclaration(
options, semanticModel, currentRoot, t.declarator,
t.identifier, currentNode, declarationsToRemove, document.Project.Solution.Workspace,
cancellationToken),
cancellationToken).ConfigureAwait(false);
}
private static (VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode invocationOrCreation) FindDiagnosticNodes(
Diagnostic diagnostic, CancellationToken cancellationToken)
{
// Recover the nodes we care about.
var declaratorLocation = diagnostic.AdditionalLocations[0];
var identifierLocation = diagnostic.AdditionalLocations[1];
var invocationOrCreationLocation = diagnostic.AdditionalLocations[2];
var declarator = (VariableDeclaratorSyntax)declaratorLocation.FindNode(cancellationToken);
var identifier = (IdentifierNameSyntax)identifierLocation.FindNode(cancellationToken);
var invocationOrCreation = (ExpressionSyntax)invocationOrCreationLocation.FindNode(
getInnermostNodeForTie: true, cancellationToken: cancellationToken);
return (declarator, identifier, invocationOrCreation);
}
private static SyntaxNode ReplaceIdentifierWithInlineDeclaration(
OptionSet options, SemanticModel semanticModel,
SyntaxNode currentRoot, VariableDeclaratorSyntax declarator,
IdentifierNameSyntax identifier, SyntaxNode currentNode,
HashSet<StatementSyntax> declarationsToRemove, Workspace workspace,
CancellationToken cancellationToken)
{
declarator = currentRoot.GetCurrentNode(declarator);
identifier = currentRoot.GetCurrentNode(identifier);
var editor = new SyntaxEditor(currentRoot, workspace);
var sourceText = currentRoot.GetText();
var declaration = (VariableDeclarationSyntax)declarator.Parent;
var singleDeclarator = declaration.Variables.Count == 1;
if (singleDeclarator)
{
// This was a local statement with a single variable in it. Just Remove
// the entire local declaration statement. Note that comments belonging to
// this local statement will be moved to be above the statement containing
// the out-var.
var localDeclarationStatement = (LocalDeclarationStatementSyntax)declaration.Parent;
var block = (BlockSyntax)localDeclarationStatement.Parent;
var declarationIndex = block.Statements.IndexOf(localDeclarationStatement);
// Try to find a predecessor Statement on the same line that isn't going to be removed
StatementSyntax priorStatementSyntax = null;
var localDeclarationToken = localDeclarationStatement.GetFirstToken();
for (var i = declarationIndex - 1; i >= 0; i--)
{
var statementSyntax = block.Statements[i];
if (declarationsToRemove.Contains(statementSyntax))
{
continue;
}
if (sourceText.AreOnSameLine(statementSyntax.GetLastToken(), localDeclarationToken))
{
priorStatementSyntax = statementSyntax;
}
break;
}
if (priorStatementSyntax != null)
{
// There's another statement on the same line as this declaration statement.
// i.e. int a; int b;
//
// Just move all trivia from our statement to be trailing trivia of the previous
// statement
editor.ReplaceNode(
priorStatementSyntax,
(s, g) => s.WithAppendedTrailingTrivia(localDeclarationStatement.GetTrailingTrivia()));
}
else
{
// Trivia on the local declaration will move to the next statement.
// use the callback form as the next statement may be the place where we're
// inlining the declaration, and thus need to see the effects of that change.
// Find the next Statement that isn't going to be removed.
// We initialize this to null here but we must see at least the statement
// into which the declaration is going to be inlined so this will be not null
StatementSyntax nextStatementSyntax = null;
for (var i = declarationIndex + 1; i < block.Statements.Count; i++)
{
var statement = block.Statements[i];
if (!declarationsToRemove.Contains(statement))
{
nextStatementSyntax = statement;
break;
}
}
editor.ReplaceNode(
nextStatementSyntax,
(s, g) => s.WithPrependedNonIndentationTriviaFrom(localDeclarationStatement));
}
editor.RemoveNode(localDeclarationStatement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
else
{
// Otherwise, just remove the single declarator. Note: we'll move the comments
// 'on' the declarator to the out-var location. This is a little bit trickier
// than normal due to how our comment-association rules work. i.e. if you have:
//
// var /*c1*/ i /*c2*/, /*c3*/ j /*c4*/;
//
// In this case 'c1' is owned by the 'var' token, not 'i', and 'c3' is owned by
// the comment token not 'j'.
editor.RemoveNode(declarator);
if (declarator == declaration.Variables[0])
{
// If we're removing the first declarator, and it's on the same line
// as the previous token, then we want to remove all the trivia belonging
// to the previous token. We're going to move it along with this declarator.
// If we don't, then the comment will stay with the previous token.
//
// Note that the moving of the comment happens later on when we make the
// declaration expression.
if (sourceText.AreOnSameLine(declarator.GetFirstToken(), declarator.GetFirstToken().GetPreviousToken(includeSkipped: true)))
{
editor.ReplaceNode(
declaration.Type,
(t, g) => t.WithTrailingTrivia(SyntaxFactory.ElasticSpace).WithoutAnnotations(Formatter.Annotation));
}
}
}
// get the type that we want to put in the out-var-decl based on the user's options.
// i.e. prefer 'out var' if that is what the user wants. Note: if we have:
//
// Method(out var x)
//
// Then the type is not-apparent, and we should not use var if the user only wants
// it for apparent types
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
var newType = GenerateTypeSyntaxOrVar(local.Type, options);
var declarationExpression = GetDeclarationExpression(
sourceText, identifier, newType, singleDeclarator ? null : declarator);
// Check if using out-var changed problem semantics.
var semanticsChanged = SemanticsChanged(semanticModel, currentNode, identifier, declarationExpression, cancellationToken);
if (semanticsChanged)
{
// Switching to 'var' changed semantics. Just use the original type of the local.
// If the user originally wrote it something other than 'var', then use what they
// wrote. Otherwise, synthesize the actual type of the local.
var explicitType = declaration.Type.IsVar ? local.Type?.GenerateTypeSyntax() : declaration.Type;
declarationExpression = SyntaxFactory.DeclarationExpression(explicitType, declarationExpression.Designation);
}
editor.ReplaceNode(identifier, declarationExpression);
return editor.GetChangedRoot();
}
public static TypeSyntax GenerateTypeSyntaxOrVar(
ITypeSymbol symbol, OptionSet options)
{
var useVar = IsVarDesired(symbol, options);
// Note: we cannot use ".GenerateTypeSyntax()" only here. that's because we're
// actually creating a DeclarationExpression and currently the Simplifier cannot
// analyze those due to limitations between how it uses Speculative SemanticModels
// and how those don't handle new declarations well.
return useVar
? SyntaxFactory.IdentifierName("var")
: symbol.GenerateTypeSyntax();
}
private static bool IsVarDesired(ITypeSymbol type, OptionSet options)
{
// If they want it for intrinsics, and this is an intrinsic, then use var.
if (type.IsSpecialType() == true)
{
return options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value;
}
// If they want "var" whenever possible, then use "var".
return options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value;
}
private static DeclarationExpressionSyntax GetDeclarationExpression(
SourceText sourceText, IdentifierNameSyntax identifier,
TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt)
{
var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier);
if (declaratorOpt != null)
{
// We're removing a single declarator. Copy any comments it has to the out-var.
//
// Note: this is tricky due to comment ownership. We want the comments that logically
// belong to the declarator, even if our syntax model attaches them to other tokens.
var precedingTrivia = declaratorOpt.GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine: true);
if (precedingTrivia.Any(t => t.IsSingleOrMultiLineComment()))
{
designation = designation.WithPrependedLeadingTrivia(MassageTrivia(precedingTrivia));
}
if (declaratorOpt.GetTrailingTrivia().Any(t => t.IsSingleOrMultiLineComment()))
{
designation = designation.WithAppendedTrailingTrivia(MassageTrivia(declaratorOpt.GetTrailingTrivia()));
}
}
newType = newType.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation);
// We need trivia between the type declaration and designation or this will generate
// "out inti", but we might have trivia in the form of comments etc from the original
// designation and in those cases adding elastic trivia will break formatting.
if (!designation.HasLeadingTrivia)
{
newType = newType.WithAppendedTrailingTrivia(SyntaxFactory.ElasticSpace);
}
return SyntaxFactory.DeclarationExpression(newType, designation);
}
private static IEnumerable<SyntaxTrivia> MassageTrivia(IEnumerable<SyntaxTrivia> triviaList)
{
foreach (var trivia in triviaList)
{
if (trivia.IsSingleOrMultiLineComment())
{
yield return trivia;
}
else if (trivia.IsWhitespace())
{
// Condense whitespace down to single spaces. We don't want things like
// indentation spaces to be inserted in the out-var location. It is appropriate
// though to have single spaces to help separate out things like comments and
// tokens though.
yield return SyntaxFactory.Space;
}
}
}
private static bool SemanticsChanged(
SemanticModel semanticModel,
SyntaxNode nodeToReplace,
IdentifierNameSyntax identifier,
DeclarationExpressionSyntax declarationExpression,
CancellationToken cancellationToken)
{
if (declarationExpression.Type.IsVar)
{
// Options want us to use 'var' if we can. Make sure we didn't change
// the semantics of the call by doing this.
// Find the symbol that the existing invocation points to.
var previousSymbol = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken).Symbol;
// Now, create a speculative model in which we make the change. Make sure
// we still point to the same symbol afterwards.
var topmostContainer = GetTopmostContainer(nodeToReplace);
if (topmostContainer == null)
{
// Couldn't figure out what we were contained in. Have to assume that semantics
// Are changing.
return true;
}
var annotation = new SyntaxAnnotation();
var updatedTopmostContainer = topmostContainer.ReplaceNode(
nodeToReplace, nodeToReplace.ReplaceNode(identifier, declarationExpression)
.WithAdditionalAnnotations(annotation));
if (!TryGetSpeculativeSemanticModel(semanticModel,
topmostContainer.SpanStart, updatedTopmostContainer, out var speculativeModel))
{
// Couldn't figure out the new semantics. Assume semantics changed.
return true;
}
var updatedInvocationOrCreation = updatedTopmostContainer.GetAnnotatedNodes(annotation).Single();
var updatedSymbolInfo = speculativeModel.GetSymbolInfo(updatedInvocationOrCreation, cancellationToken);
if (!SymbolEquivalenceComparer.Instance.Equals(previousSymbol, updatedSymbolInfo.Symbol))
{
// We're pointing at a new symbol now. Semantic have changed.
return true;
}
}
return false;
}
private static SyntaxNode GetTopmostContainer(SyntaxNode expression)
{
return expression.GetAncestorsOrThis(
a => a is StatementSyntax ||
a is EqualsValueClauseSyntax ||
a is ArrowExpressionClauseSyntax ||
a is ConstructorInitializerSyntax).LastOrDefault();
}
private static bool TryGetSpeculativeSemanticModel(
SemanticModel semanticModel,
int position, SyntaxNode topmostContainer,
out SemanticModel speculativeModel)
{
switch (topmostContainer)
{
case StatementSyntax statement:
return semanticModel.TryGetSpeculativeSemanticModel(position, statement, out speculativeModel);
case EqualsValueClauseSyntax equalsValue:
return semanticModel.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel);
case ArrowExpressionClauseSyntax arrowExpression:
return semanticModel.TryGetSpeculativeSemanticModel(position, arrowExpression, out speculativeModel);
case ConstructorInitializerSyntax constructorInitializer:
return semanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel);
}
speculativeModel = null;
return false;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Inline_variable_declaration,
createChangedDocument,
CSharpAnalyzersResources.Inline_variable_declaration)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
#endif
namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InlineDeclaration), Shared]
internal partial class CSharpInlineDeclarationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpInlineDeclarationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.InlineDeclarationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
// Gather all statements to be removed
// We need this to find the statements we can safely attach trivia to
var declarationsToRemove = new HashSet<StatementSyntax>();
foreach (var diagnostic in diagnostics)
{
declarationsToRemove.Add((LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken).Parent.Parent);
}
// Attempt to use an out-var declaration if that's the style the user prefers.
// Note: if using 'var' would cause a problem, we will use the actual type
// of the local. This is necessary in some cases (for example, when the
// type of the out-var-decl affects overload resolution or generic instantiation).
var originalRoot = editor.OriginalRoot;
var originalNodes = diagnostics.SelectAsArray(diagnostic => FindDiagnosticNodes(diagnostic, cancellationToken));
await editor.ApplyExpressionLevelSemanticEditsAsync(
document,
originalNodes,
t =>
{
using var additionalNodesToTrackDisposer = ArrayBuilder<SyntaxNode>.GetInstance(capacity: 2, out var additionalNodesToTrack);
additionalNodesToTrack.Add(t.identifier);
additionalNodesToTrack.Add(t.declarator);
return (t.invocationOrCreation, additionalNodesToTrack.ToImmutable());
},
(_1, _2, _3) => true,
(semanticModel, currentRoot, t, currentNode)
=> ReplaceIdentifierWithInlineDeclaration(
options, semanticModel, currentRoot, t.declarator,
t.identifier, currentNode, declarationsToRemove, document.Project.Solution.Workspace,
cancellationToken),
cancellationToken).ConfigureAwait(false);
}
private static (VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode invocationOrCreation) FindDiagnosticNodes(
Diagnostic diagnostic, CancellationToken cancellationToken)
{
// Recover the nodes we care about.
var declaratorLocation = diagnostic.AdditionalLocations[0];
var identifierLocation = diagnostic.AdditionalLocations[1];
var invocationOrCreationLocation = diagnostic.AdditionalLocations[2];
var declarator = (VariableDeclaratorSyntax)declaratorLocation.FindNode(cancellationToken);
var identifier = (IdentifierNameSyntax)identifierLocation.FindNode(cancellationToken);
var invocationOrCreation = (ExpressionSyntax)invocationOrCreationLocation.FindNode(
getInnermostNodeForTie: true, cancellationToken: cancellationToken);
return (declarator, identifier, invocationOrCreation);
}
private static SyntaxNode ReplaceIdentifierWithInlineDeclaration(
OptionSet options, SemanticModel semanticModel,
SyntaxNode currentRoot, VariableDeclaratorSyntax declarator,
IdentifierNameSyntax identifier, SyntaxNode currentNode,
HashSet<StatementSyntax> declarationsToRemove, Workspace workspace,
CancellationToken cancellationToken)
{
declarator = currentRoot.GetCurrentNode(declarator);
identifier = currentRoot.GetCurrentNode(identifier);
var editor = new SyntaxEditor(currentRoot, workspace);
var sourceText = currentRoot.GetText();
var declaration = (VariableDeclarationSyntax)declarator.Parent;
var singleDeclarator = declaration.Variables.Count == 1;
if (singleDeclarator)
{
// This was a local statement with a single variable in it. Just Remove
// the entire local declaration statement. Note that comments belonging to
// this local statement will be moved to be above the statement containing
// the out-var.
var localDeclarationStatement = (LocalDeclarationStatementSyntax)declaration.Parent;
var block = (BlockSyntax)localDeclarationStatement.Parent;
var declarationIndex = block.Statements.IndexOf(localDeclarationStatement);
// Try to find a predecessor Statement on the same line that isn't going to be removed
StatementSyntax priorStatementSyntax = null;
var localDeclarationToken = localDeclarationStatement.GetFirstToken();
for (var i = declarationIndex - 1; i >= 0; i--)
{
var statementSyntax = block.Statements[i];
if (declarationsToRemove.Contains(statementSyntax))
{
continue;
}
if (sourceText.AreOnSameLine(statementSyntax.GetLastToken(), localDeclarationToken))
{
priorStatementSyntax = statementSyntax;
}
break;
}
if (priorStatementSyntax != null)
{
// There's another statement on the same line as this declaration statement.
// i.e. int a; int b;
//
// Just move all trivia from our statement to be trailing trivia of the previous
// statement
editor.ReplaceNode(
priorStatementSyntax,
(s, g) => s.WithAppendedTrailingTrivia(localDeclarationStatement.GetTrailingTrivia()));
}
else
{
// Trivia on the local declaration will move to the next statement.
// use the callback form as the next statement may be the place where we're
// inlining the declaration, and thus need to see the effects of that change.
// Find the next Statement that isn't going to be removed.
// We initialize this to null here but we must see at least the statement
// into which the declaration is going to be inlined so this will be not null
StatementSyntax nextStatementSyntax = null;
for (var i = declarationIndex + 1; i < block.Statements.Count; i++)
{
var statement = block.Statements[i];
if (!declarationsToRemove.Contains(statement))
{
nextStatementSyntax = statement;
break;
}
}
editor.ReplaceNode(
nextStatementSyntax,
(s, g) => s.WithPrependedNonIndentationTriviaFrom(localDeclarationStatement));
}
editor.RemoveNode(localDeclarationStatement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
else
{
// Otherwise, just remove the single declarator. Note: we'll move the comments
// 'on' the declarator to the out-var location. This is a little bit trickier
// than normal due to how our comment-association rules work. i.e. if you have:
//
// var /*c1*/ i /*c2*/, /*c3*/ j /*c4*/;
//
// In this case 'c1' is owned by the 'var' token, not 'i', and 'c3' is owned by
// the comment token not 'j'.
editor.RemoveNode(declarator);
if (declarator == declaration.Variables[0])
{
// If we're removing the first declarator, and it's on the same line
// as the previous token, then we want to remove all the trivia belonging
// to the previous token. We're going to move it along with this declarator.
// If we don't, then the comment will stay with the previous token.
//
// Note that the moving of the comment happens later on when we make the
// declaration expression.
if (sourceText.AreOnSameLine(declarator.GetFirstToken(), declarator.GetFirstToken().GetPreviousToken(includeSkipped: true)))
{
editor.ReplaceNode(
declaration.Type,
(t, g) => t.WithTrailingTrivia(SyntaxFactory.ElasticSpace).WithoutAnnotations(Formatter.Annotation));
}
}
}
// get the type that we want to put in the out-var-decl based on the user's options.
// i.e. prefer 'out var' if that is what the user wants. Note: if we have:
//
// Method(out var x)
//
// Then the type is not-apparent, and we should not use var if the user only wants
// it for apparent types
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
var newType = GenerateTypeSyntaxOrVar(local.Type, options);
var declarationExpression = GetDeclarationExpression(
sourceText, identifier, newType, singleDeclarator ? null : declarator);
// Check if using out-var changed problem semantics.
var semanticsChanged = SemanticsChanged(semanticModel, currentNode, identifier, declarationExpression, cancellationToken);
if (semanticsChanged)
{
// Switching to 'var' changed semantics. Just use the original type of the local.
// If the user originally wrote it something other than 'var', then use what they
// wrote. Otherwise, synthesize the actual type of the local.
var explicitType = declaration.Type.IsVar ? local.Type?.GenerateTypeSyntax() : declaration.Type;
declarationExpression = SyntaxFactory.DeclarationExpression(explicitType, declarationExpression.Designation);
}
editor.ReplaceNode(identifier, declarationExpression);
return editor.GetChangedRoot();
}
public static TypeSyntax GenerateTypeSyntaxOrVar(
ITypeSymbol symbol, OptionSet options)
{
var useVar = IsVarDesired(symbol, options);
// Note: we cannot use ".GenerateTypeSyntax()" only here. that's because we're
// actually creating a DeclarationExpression and currently the Simplifier cannot
// analyze those due to limitations between how it uses Speculative SemanticModels
// and how those don't handle new declarations well.
return useVar
? SyntaxFactory.IdentifierName("var")
: symbol.GenerateTypeSyntax();
}
private static bool IsVarDesired(ITypeSymbol type, OptionSet options)
{
// If they want it for intrinsics, and this is an intrinsic, then use var.
if (type.IsSpecialType() == true)
{
return options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value;
}
// If they want "var" whenever possible, then use "var".
return options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value;
}
private static DeclarationExpressionSyntax GetDeclarationExpression(
SourceText sourceText, IdentifierNameSyntax identifier,
TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt)
{
var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier);
if (declaratorOpt != null)
{
// We're removing a single declarator. Copy any comments it has to the out-var.
//
// Note: this is tricky due to comment ownership. We want the comments that logically
// belong to the declarator, even if our syntax model attaches them to other tokens.
var precedingTrivia = declaratorOpt.GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine: true);
if (precedingTrivia.Any(t => t.IsSingleOrMultiLineComment()))
{
designation = designation.WithPrependedLeadingTrivia(MassageTrivia(precedingTrivia));
}
if (declaratorOpt.GetTrailingTrivia().Any(t => t.IsSingleOrMultiLineComment()))
{
designation = designation.WithAppendedTrailingTrivia(MassageTrivia(declaratorOpt.GetTrailingTrivia()));
}
}
newType = newType.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation);
// We need trivia between the type declaration and designation or this will generate
// "out inti", but we might have trivia in the form of comments etc from the original
// designation and in those cases adding elastic trivia will break formatting.
if (!designation.HasLeadingTrivia)
{
newType = newType.WithAppendedTrailingTrivia(SyntaxFactory.ElasticSpace);
}
return SyntaxFactory.DeclarationExpression(newType, designation);
}
private static IEnumerable<SyntaxTrivia> MassageTrivia(IEnumerable<SyntaxTrivia> triviaList)
{
foreach (var trivia in triviaList)
{
if (trivia.IsSingleOrMultiLineComment())
{
yield return trivia;
}
else if (trivia.IsWhitespace())
{
// Condense whitespace down to single spaces. We don't want things like
// indentation spaces to be inserted in the out-var location. It is appropriate
// though to have single spaces to help separate out things like comments and
// tokens though.
yield return SyntaxFactory.Space;
}
}
}
private static bool SemanticsChanged(
SemanticModel semanticModel,
SyntaxNode nodeToReplace,
IdentifierNameSyntax identifier,
DeclarationExpressionSyntax declarationExpression,
CancellationToken cancellationToken)
{
if (declarationExpression.Type.IsVar)
{
// Options want us to use 'var' if we can. Make sure we didn't change
// the semantics of the call by doing this.
// Find the symbol that the existing invocation points to.
var previousSymbol = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken).Symbol;
// Now, create a speculative model in which we make the change. Make sure
// we still point to the same symbol afterwards.
var topmostContainer = GetTopmostContainer(nodeToReplace);
if (topmostContainer == null)
{
// Couldn't figure out what we were contained in. Have to assume that semantics
// Are changing.
return true;
}
var annotation = new SyntaxAnnotation();
var updatedTopmostContainer = topmostContainer.ReplaceNode(
nodeToReplace, nodeToReplace.ReplaceNode(identifier, declarationExpression)
.WithAdditionalAnnotations(annotation));
if (!TryGetSpeculativeSemanticModel(semanticModel,
topmostContainer.SpanStart, updatedTopmostContainer, out var speculativeModel))
{
// Couldn't figure out the new semantics. Assume semantics changed.
return true;
}
var updatedInvocationOrCreation = updatedTopmostContainer.GetAnnotatedNodes(annotation).Single();
var updatedSymbolInfo = speculativeModel.GetSymbolInfo(updatedInvocationOrCreation, cancellationToken);
if (!SymbolEquivalenceComparer.Instance.Equals(previousSymbol, updatedSymbolInfo.Symbol))
{
// We're pointing at a new symbol now. Semantic have changed.
return true;
}
}
return false;
}
private static SyntaxNode GetTopmostContainer(SyntaxNode expression)
{
return expression.GetAncestorsOrThis(
a => a is StatementSyntax ||
a is EqualsValueClauseSyntax ||
a is ArrowExpressionClauseSyntax ||
a is ConstructorInitializerSyntax).LastOrDefault();
}
private static bool TryGetSpeculativeSemanticModel(
SemanticModel semanticModel,
int position, SyntaxNode topmostContainer,
out SemanticModel speculativeModel)
{
switch (topmostContainer)
{
case StatementSyntax statement:
return semanticModel.TryGetSpeculativeSemanticModel(position, statement, out speculativeModel);
case EqualsValueClauseSyntax equalsValue:
return semanticModel.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel);
case ArrowExpressionClauseSyntax arrowExpression:
return semanticModel.TryGetSpeculativeSemanticModel(position, arrowExpression, out speculativeModel);
case ConstructorInitializerSyntax constructorInitializer:
return semanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel);
}
speculativeModel = null;
return false;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Inline_variable_declaration,
createChangedDocument,
CSharpAnalyzersResources.Inline_variable_declaration)
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/LoadKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ContextQuery;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class LoadKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public LoadKeywordRecommender()
: base(SyntaxKind.LoadKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsPreProcessorKeywordContext &&
syntaxTree.IsScript() &&
syntaxTree.IsBeforeFirstToken(position, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class LoadKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public LoadKeywordRecommender()
: base(SyntaxKind.LoadKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsPreProcessorKeywordContext &&
syntaxTree.IsScript() &&
syntaxTree.IsBeforeFirstToken(position, cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxToken.SyntaxLiteral.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Utilities;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial class SyntaxToken
{
internal class SyntaxTokenWithValue<T> : SyntaxToken
{
protected readonly string TextField;
protected readonly T ValueField;
internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value)
: base(kind, text.Length)
{
this.TextField = text;
this.ValueField = value;
}
internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)
: base(kind, text.Length, diagnostics, annotations)
{
this.TextField = text;
this.ValueField = value;
}
internal SyntaxTokenWithValue(ObjectReader reader)
: base(reader)
{
this.TextField = reader.ReadString();
this.FullWidth = this.TextField.Length;
this.ValueField = (T)reader.ReadValue();
}
static SyntaxTokenWithValue()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxTokenWithValue<T>), r => new SyntaxTokenWithValue<T>(r));
}
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteString(this.TextField);
writer.WriteValue(this.ValueField);
}
public override string Text
{
get
{
return this.TextField;
}
}
public override object Value
{
get
{
return this.ValueField;
}
}
public override string ValueText
{
get
{
return Convert.ToString(this.ValueField, CultureInfo.InvariantCulture);
}
}
public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia)
{
return new SyntaxTokenWithValueAndTrivia<T>(this.Kind, this.TextField, this.ValueField, trivia, null, this.GetDiagnostics(), this.GetAnnotations());
}
public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia)
{
return new SyntaxTokenWithValueAndTrivia<T>(this.Kind, this.TextField, this.ValueField, null, trivia, this.GetDiagnostics(), this.GetAnnotations());
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics)
{
return new SyntaxTokenWithValue<T>(this.Kind, this.TextField, this.ValueField, diagnostics, this.GetAnnotations());
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations)
{
return new SyntaxTokenWithValue<T>(this.Kind, this.TextField, this.ValueField, this.GetDiagnostics(), annotations);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Utilities;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial class SyntaxToken
{
internal class SyntaxTokenWithValue<T> : SyntaxToken
{
protected readonly string TextField;
protected readonly T ValueField;
internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value)
: base(kind, text.Length)
{
this.TextField = text;
this.ValueField = value;
}
internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)
: base(kind, text.Length, diagnostics, annotations)
{
this.TextField = text;
this.ValueField = value;
}
internal SyntaxTokenWithValue(ObjectReader reader)
: base(reader)
{
this.TextField = reader.ReadString();
this.FullWidth = this.TextField.Length;
this.ValueField = (T)reader.ReadValue();
}
static SyntaxTokenWithValue()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxTokenWithValue<T>), r => new SyntaxTokenWithValue<T>(r));
}
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteString(this.TextField);
writer.WriteValue(this.ValueField);
}
public override string Text
{
get
{
return this.TextField;
}
}
public override object Value
{
get
{
return this.ValueField;
}
}
public override string ValueText
{
get
{
return Convert.ToString(this.ValueField, CultureInfo.InvariantCulture);
}
}
public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia)
{
return new SyntaxTokenWithValueAndTrivia<T>(this.Kind, this.TextField, this.ValueField, trivia, null, this.GetDiagnostics(), this.GetAnnotations());
}
public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia)
{
return new SyntaxTokenWithValueAndTrivia<T>(this.Kind, this.TextField, this.ValueField, null, trivia, this.GetDiagnostics(), this.GetAnnotations());
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics)
{
return new SyntaxTokenWithValue<T>(this.Kind, this.TextField, this.ValueField, diagnostics, this.GetAnnotations());
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations)
{
return new SyntaxTokenWithValue<T>(this.Kind, this.TextField, this.ValueField, this.GetDiagnostics(), annotations);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryParentheses/VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]>
Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider
Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean
Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(
current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]>
Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider
Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean
Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(
current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharp/CompleteStatement/CompleteStatementCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.CompleteStatement
{
/// <summary>
/// When user types <c>;</c> in a statement, semicolon is added and caret is placed after the semicolon
/// </summary>
[Export(typeof(ICommandHandler))]
[Export]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(nameof(CompleteStatementCommandHandler))]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal sealed class CompleteStatementCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>
{
private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CompleteStatementCommandHandler(ITextUndoHistoryRegistry textUndoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService)
{
_textUndoHistoryRegistry = textUndoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
public string DisplayName => CSharpEditorResources.Complete_statement_on_semicolon;
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
{
var willMoveSemicolon = BeforeExecuteCommand(speculative: true, args: args, executionContext: executionContext);
if (!willMoveSemicolon)
{
// Pass this on without altering the undo stack
nextCommandHandler();
return;
}
using var transaction = CaretPreservingEditTransaction.TryCreate(CSharpEditorResources.Complete_statement_on_semicolon, args.TextView, _textUndoHistoryRegistry, _editorOperationsFactoryService);
// Determine where semicolon should be placed and move caret to location
BeforeExecuteCommand(speculative: false, args: args, executionContext: executionContext);
// Insert the semicolon using next command handler
nextCommandHandler();
transaction.Complete();
}
private static bool BeforeExecuteCommand(bool speculative, TypeCharCommandArgs args, CommandExecutionContext executionContext)
{
if (args.TypedChar != ';' || !args.TextView.Selection.IsEmpty)
{
return false;
}
var caretOpt = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!caretOpt.HasValue)
{
return false;
}
if (!args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon))
{
return false;
}
var caret = caretOpt.Value;
var document = caret.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var root = document.GetSyntaxRootSynchronously(executionContext.OperationContext.UserCancellationToken);
var cancellationToken = executionContext.OperationContext.UserCancellationToken;
if (!TryGetStartingNode(root, caret, out var currentNode, cancellationToken))
{
return false;
}
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret: caret, caret, syntaxFacts, currentNode,
isInsideDelimiters: false, cancellationToken);
}
/// <summary>
/// Determines which node the caret is in.
/// Must be called on the UI thread.
/// </summary>
/// <param name="root"></param>
/// <param name="caret"></param>
/// <param name="startingNode"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private static bool TryGetStartingNode(SyntaxNode root, SnapshotPoint caret,
out SyntaxNode startingNode, CancellationToken cancellationToken)
{
// on the UI thread
startingNode = null;
var caretPosition = caret.Position;
var token = root.FindTokenOnLeftOfPosition(caretPosition);
if (token.SyntaxTree == null
|| token.SyntaxTree.IsEntirelyWithinComment(caretPosition, cancellationToken))
{
return false;
}
startingNode = token.Parent;
// If the caret is before an opening delimiter or after a closing delimeter,
// start analysis with node outside of delimiters.
//
// Examples,
// `obj.ToString$()` where `token` references `(` but the caret isn't actually inside the argument list.
// `obj.ToString()$` or `obj.method()$ .method()` where `token` references `)` but the caret isn't inside the argument list.
// `defa$$ult(object)` where `token` references `default` but the caret isn't inside the parentheses.
var delimiters = startingNode.GetParentheses();
if (delimiters == default)
{
delimiters = startingNode.GetBrackets();
}
var (openingDelimiter, closingDelimiter) = delimiters;
if (!openingDelimiter.IsKind(SyntaxKind.None) && openingDelimiter.Span.Start >= caretPosition
|| !closingDelimiter.IsKind(SyntaxKind.None) && closingDelimiter.Span.End <= caretPosition)
{
startingNode = startingNode.Parent;
}
return true;
}
private static bool MoveCaretToSemicolonPosition(
bool speculative,
TypeCharCommandArgs args,
Document document,
SyntaxNode root,
SnapshotPoint originalCaret,
SnapshotPoint caret,
ISyntaxFactsService syntaxFacts,
SyntaxNode currentNode,
bool isInsideDelimiters,
CancellationToken cancellationToken)
{
if (currentNode == null ||
IsInAStringOrCharacter(currentNode, caret))
{
// Don't complete statement. Return without moving the caret.
return false;
}
if (currentNode.IsKind(
SyntaxKind.ArgumentList,
SyntaxKind.ArrayRankSpecifier,
SyntaxKind.BracketedArgumentList,
SyntaxKind.ParenthesizedExpression,
SyntaxKind.ParameterList,
SyntaxKind.DefaultExpression,
SyntaxKind.CheckedExpression,
SyntaxKind.UncheckedExpression,
SyntaxKind.TypeOfExpression,
SyntaxKind.TupleExpression))
{
// make sure the closing delimiter exists
if (RequiredDelimiterIsMissing(currentNode))
{
return false;
}
// set caret to just outside the delimited span and analyze again
// if caret was already in that position, return to avoid infinite loop
var newCaretPosition = currentNode.Span.End;
if (newCaretPosition == caret.Position)
{
return false;
}
var newCaret = args.SubjectBuffer.CurrentSnapshot.GetPoint(newCaretPosition);
if (!TryGetStartingNode(root, newCaret, out currentNode, cancellationToken))
{
return false;
}
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret, newCaret, syntaxFacts, currentNode,
isInsideDelimiters: true, cancellationToken);
}
else if (currentNode.IsKind(SyntaxKind.DoStatement))
{
if (IsInConditionOfDoStatement(currentNode, caret))
{
return MoveCaretToFinalPositionInStatement(speculative, currentNode, args, originalCaret, caret, true);
}
return false;
}
else if (syntaxFacts.IsStatement(currentNode)
|| CanHaveSemicolon(currentNode))
{
return MoveCaretToFinalPositionInStatement(speculative, currentNode, args, originalCaret, caret, isInsideDelimiters);
}
else
{
// keep caret the same, but continue analyzing with the parent of the current node
currentNode = currentNode.Parent;
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret, caret, syntaxFacts, currentNode,
isInsideDelimiters, cancellationToken);
}
}
private static bool CanHaveSemicolon(SyntaxNode currentNode)
{
if (currentNode.IsKind(SyntaxKind.FieldDeclaration, SyntaxKind.DelegateDeclaration, SyntaxKind.ArrowExpressionClause))
{
return true;
}
if (currentNode is RecordDeclarationSyntax { OpenBraceToken: { IsMissing: true } })
{
return true;
}
if (currentNode is MethodDeclarationSyntax method)
{
if (method.Modifiers.Any(SyntaxKind.AbstractKeyword) || method.Modifiers.Any(SyntaxKind.ExternKeyword) ||
method.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
return true;
}
if (method.Modifiers.Any(SyntaxKind.PartialKeyword) && method.Body is null)
{
return true;
}
}
return false;
}
private static bool IsInConditionOfDoStatement(SyntaxNode currentNode, SnapshotPoint caret)
{
if (!currentNode.IsKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement))
{
return false;
}
var condition = doStatement.Condition;
return (caret >= condition.Span.Start && caret <= condition.Span.End);
}
private static bool MoveCaretToFinalPositionInStatement(bool speculative, SyntaxNode statementNode, TypeCharCommandArgs args, SnapshotPoint originalCaret, SnapshotPoint caret, bool isInsideDelimiters)
{
if (StatementClosingDelimiterIsMissing(statementNode))
{
// Don't complete statement. Return without moving the caret.
return false;
}
if (TryGetCaretPositionToMove(statementNode, caret, isInsideDelimiters, out var targetPosition)
&& targetPosition != originalCaret)
{
if (speculative)
{
// Return an indication that moving the caret is required, but don't actually move it
return true;
}
Logger.Log(FunctionId.CommandHandler_CompleteStatement, KeyValueLogMessage.Create(LogType.UserAction, m =>
{
m[nameof(isInsideDelimiters)] = isInsideDelimiters;
m[nameof(statementNode)] = statementNode.Kind();
}));
return args.TextView.TryMoveCaretToAndEnsureVisible(targetPosition);
}
return false;
}
private static bool TryGetCaretPositionToMove(SyntaxNode statementNode, SnapshotPoint caret, bool isInsideDelimiters, out SnapshotPoint targetPosition)
{
targetPosition = default;
switch (statementNode.Kind())
{
case SyntaxKind.DoStatement:
// Move caret after the do statement's closing paren.
targetPosition = caret.Snapshot.GetPoint(((DoStatementSyntax)statementNode).CloseParenToken.Span.End);
return true;
case SyntaxKind.ForStatement:
// `For` statements can have semicolon after initializer/declaration or after condition.
// If caret is in initialer/declaration or condition, AND is inside other delimiters, complete statement
// Otherwise, return without moving the caret.
return isInsideDelimiters && TryGetForStatementCaret(caret, (ForStatementSyntax)statementNode, out targetPosition);
case SyntaxKind.ExpressionStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.LocalDeclarationStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.ArrowExpressionClause:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
// These statement types end in a semicolon.
// if the original caret was inside any delimiters, `caret` will be after the outermost delimiter
targetPosition = caret;
return isInsideDelimiters;
default:
// For all other statement types, don't complete statement. Return without moving the caret.
return false;
}
}
private static bool TryGetForStatementCaret(SnapshotPoint originalCaret, ForStatementSyntax forStatement, out SnapshotPoint forStatementCaret)
{
if (CaretIsInForStatementCondition(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Condition.Span.End);
}
else if (CaretIsInForStatementDeclaration(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Declaration.Span.End);
}
else if (CaretIsInForStatementInitializers(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Initializers.Span.End);
}
else
{
// set caret to default, we will return false
forStatementCaret = default;
}
return (forStatementCaret != default);
// Locals
SnapshotPoint GetCaretAtPosition(int position) => originalCaret.Snapshot.GetPoint(position);
}
private static bool CaretIsInForStatementCondition(int caretPosition, ForStatementSyntax forStatementSyntax)
// If condition is null and caret is in the condition section, as in `for ( ; $$; )`,
// we will have bailed earlier due to not being inside supported delimiters
=> forStatementSyntax.Condition == null
? false
: caretPosition > forStatementSyntax.Condition.SpanStart &&
caretPosition <= forStatementSyntax.Condition.Span.End;
private static bool CaretIsInForStatementDeclaration(int caretPosition, ForStatementSyntax forStatementSyntax)
=> forStatementSyntax.Declaration != null &&
caretPosition > forStatementSyntax.Declaration.Span.Start &&
caretPosition <= forStatementSyntax.Declaration.Span.End;
private static bool CaretIsInForStatementInitializers(int caretPosition, ForStatementSyntax forStatementSyntax)
=> forStatementSyntax.Initializers.Count != 0 &&
caretPosition > forStatementSyntax.Initializers.Span.Start &&
caretPosition <= forStatementSyntax.Initializers.Span.End;
private static bool IsInAStringOrCharacter(SyntaxNode currentNode, SnapshotPoint caret)
// Check to see if caret is before or after string
=> currentNode.IsKind(SyntaxKind.InterpolatedStringExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression)
&& caret.Position < currentNode.Span.End
&& caret.Position > currentNode.SpanStart;
/// <summary>
/// Determines if a statement ends with a closing delimiter, and that closing delimiter exists.
/// </summary>
/// <remarks>
/// <para>Statements such as <c>do { } while (expression);</c> contain embedded enclosing delimiters immediately
/// preceding the semicolon. These delimiters are not part of the expression, but they behave like an argument
/// list for the purposes of identifying relevant places for statement completion:</para>
/// <list type="bullet">
/// <item><description>The closing delimiter is typically inserted by the Automatic Brace Completion feature.</description></item>
/// <item><description>It is not syntactically valid to place a semicolon <em>directly</em> within the delimiters.</description></item>
/// </list>
/// </remarks>
/// <param name="currentNode"></param>
/// <returns><see langword="true"/> if <paramref name="currentNode"/> is a statement that ends with a closing
/// delimiter, and that closing delimiter exists in the source code; otherwise, <see langword="false"/>.
/// </returns>
private static bool StatementClosingDelimiterIsMissing(SyntaxNode currentNode)
{
switch (currentNode.Kind())
{
case SyntaxKind.DoStatement:
var dostatement = (DoStatementSyntax)currentNode;
return dostatement.CloseParenToken.IsMissing;
case SyntaxKind.ForStatement:
var forStatement = (ForStatementSyntax)currentNode;
return forStatement.CloseParenToken.IsMissing;
default:
return false;
}
}
/// <summary>
/// Determines if a syntax node includes all required closing delimiters.
/// </summary>
/// <remarks>
/// <para>Some syntax nodes, such as parenthesized expressions, require a matching closing delimiter to end the
/// syntax node. If this node is omitted from the source code, the parser will automatically insert a zero-width
/// "missing" closing delimiter token to produce a valid syntax tree. This method determines if required closing
/// delimiters are present in the original source.</para>
/// </remarks>
/// <param name="currentNode"></param>
/// <returns>
/// <list type="bullet">
/// <item><description><see langword="true"/> if <paramref name="currentNode"/> requires a closing delimiter and the closing delimiter is present in the source (i.e. not missing)</description></item>
/// <item><description><see langword="true"/> if <paramref name="currentNode"/> does not require a closing delimiter</description></item>
/// <item><description>otherwise, <see langword="false"/>.</description></item>
/// </list>
/// </returns>
private static bool RequiredDelimiterIsMissing(SyntaxNode currentNode)
{
return currentNode.GetBrackets().closeBracket.IsMissing ||
currentNode.GetParentheses().closeParen.IsMissing;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.CompleteStatement
{
/// <summary>
/// When user types <c>;</c> in a statement, semicolon is added and caret is placed after the semicolon
/// </summary>
[Export(typeof(ICommandHandler))]
[Export]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(nameof(CompleteStatementCommandHandler))]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal sealed class CompleteStatementCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>
{
private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CompleteStatementCommandHandler(ITextUndoHistoryRegistry textUndoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService)
{
_textUndoHistoryRegistry = textUndoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
public string DisplayName => CSharpEditorResources.Complete_statement_on_semicolon;
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
{
var willMoveSemicolon = BeforeExecuteCommand(speculative: true, args: args, executionContext: executionContext);
if (!willMoveSemicolon)
{
// Pass this on without altering the undo stack
nextCommandHandler();
return;
}
using var transaction = CaretPreservingEditTransaction.TryCreate(CSharpEditorResources.Complete_statement_on_semicolon, args.TextView, _textUndoHistoryRegistry, _editorOperationsFactoryService);
// Determine where semicolon should be placed and move caret to location
BeforeExecuteCommand(speculative: false, args: args, executionContext: executionContext);
// Insert the semicolon using next command handler
nextCommandHandler();
transaction.Complete();
}
private static bool BeforeExecuteCommand(bool speculative, TypeCharCommandArgs args, CommandExecutionContext executionContext)
{
if (args.TypedChar != ';' || !args.TextView.Selection.IsEmpty)
{
return false;
}
var caretOpt = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!caretOpt.HasValue)
{
return false;
}
if (!args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon))
{
return false;
}
var caret = caretOpt.Value;
var document = caret.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var root = document.GetSyntaxRootSynchronously(executionContext.OperationContext.UserCancellationToken);
var cancellationToken = executionContext.OperationContext.UserCancellationToken;
if (!TryGetStartingNode(root, caret, out var currentNode, cancellationToken))
{
return false;
}
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret: caret, caret, syntaxFacts, currentNode,
isInsideDelimiters: false, cancellationToken);
}
/// <summary>
/// Determines which node the caret is in.
/// Must be called on the UI thread.
/// </summary>
/// <param name="root"></param>
/// <param name="caret"></param>
/// <param name="startingNode"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private static bool TryGetStartingNode(SyntaxNode root, SnapshotPoint caret,
out SyntaxNode startingNode, CancellationToken cancellationToken)
{
// on the UI thread
startingNode = null;
var caretPosition = caret.Position;
var token = root.FindTokenOnLeftOfPosition(caretPosition);
if (token.SyntaxTree == null
|| token.SyntaxTree.IsEntirelyWithinComment(caretPosition, cancellationToken))
{
return false;
}
startingNode = token.Parent;
// If the caret is before an opening delimiter or after a closing delimeter,
// start analysis with node outside of delimiters.
//
// Examples,
// `obj.ToString$()` where `token` references `(` but the caret isn't actually inside the argument list.
// `obj.ToString()$` or `obj.method()$ .method()` where `token` references `)` but the caret isn't inside the argument list.
// `defa$$ult(object)` where `token` references `default` but the caret isn't inside the parentheses.
var delimiters = startingNode.GetParentheses();
if (delimiters == default)
{
delimiters = startingNode.GetBrackets();
}
var (openingDelimiter, closingDelimiter) = delimiters;
if (!openingDelimiter.IsKind(SyntaxKind.None) && openingDelimiter.Span.Start >= caretPosition
|| !closingDelimiter.IsKind(SyntaxKind.None) && closingDelimiter.Span.End <= caretPosition)
{
startingNode = startingNode.Parent;
}
return true;
}
private static bool MoveCaretToSemicolonPosition(
bool speculative,
TypeCharCommandArgs args,
Document document,
SyntaxNode root,
SnapshotPoint originalCaret,
SnapshotPoint caret,
ISyntaxFactsService syntaxFacts,
SyntaxNode currentNode,
bool isInsideDelimiters,
CancellationToken cancellationToken)
{
if (currentNode == null ||
IsInAStringOrCharacter(currentNode, caret))
{
// Don't complete statement. Return without moving the caret.
return false;
}
if (currentNode.IsKind(
SyntaxKind.ArgumentList,
SyntaxKind.ArrayRankSpecifier,
SyntaxKind.BracketedArgumentList,
SyntaxKind.ParenthesizedExpression,
SyntaxKind.ParameterList,
SyntaxKind.DefaultExpression,
SyntaxKind.CheckedExpression,
SyntaxKind.UncheckedExpression,
SyntaxKind.TypeOfExpression,
SyntaxKind.TupleExpression))
{
// make sure the closing delimiter exists
if (RequiredDelimiterIsMissing(currentNode))
{
return false;
}
// set caret to just outside the delimited span and analyze again
// if caret was already in that position, return to avoid infinite loop
var newCaretPosition = currentNode.Span.End;
if (newCaretPosition == caret.Position)
{
return false;
}
var newCaret = args.SubjectBuffer.CurrentSnapshot.GetPoint(newCaretPosition);
if (!TryGetStartingNode(root, newCaret, out currentNode, cancellationToken))
{
return false;
}
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret, newCaret, syntaxFacts, currentNode,
isInsideDelimiters: true, cancellationToken);
}
else if (currentNode.IsKind(SyntaxKind.DoStatement))
{
if (IsInConditionOfDoStatement(currentNode, caret))
{
return MoveCaretToFinalPositionInStatement(speculative, currentNode, args, originalCaret, caret, true);
}
return false;
}
else if (syntaxFacts.IsStatement(currentNode)
|| CanHaveSemicolon(currentNode))
{
return MoveCaretToFinalPositionInStatement(speculative, currentNode, args, originalCaret, caret, isInsideDelimiters);
}
else
{
// keep caret the same, but continue analyzing with the parent of the current node
currentNode = currentNode.Parent;
return MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret, caret, syntaxFacts, currentNode,
isInsideDelimiters, cancellationToken);
}
}
private static bool CanHaveSemicolon(SyntaxNode currentNode)
{
if (currentNode.IsKind(SyntaxKind.FieldDeclaration, SyntaxKind.DelegateDeclaration, SyntaxKind.ArrowExpressionClause))
{
return true;
}
if (currentNode is RecordDeclarationSyntax { OpenBraceToken: { IsMissing: true } })
{
return true;
}
if (currentNode is MethodDeclarationSyntax method)
{
if (method.Modifiers.Any(SyntaxKind.AbstractKeyword) || method.Modifiers.Any(SyntaxKind.ExternKeyword) ||
method.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
return true;
}
if (method.Modifiers.Any(SyntaxKind.PartialKeyword) && method.Body is null)
{
return true;
}
}
return false;
}
private static bool IsInConditionOfDoStatement(SyntaxNode currentNode, SnapshotPoint caret)
{
if (!currentNode.IsKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement))
{
return false;
}
var condition = doStatement.Condition;
return (caret >= condition.Span.Start && caret <= condition.Span.End);
}
private static bool MoveCaretToFinalPositionInStatement(bool speculative, SyntaxNode statementNode, TypeCharCommandArgs args, SnapshotPoint originalCaret, SnapshotPoint caret, bool isInsideDelimiters)
{
if (StatementClosingDelimiterIsMissing(statementNode))
{
// Don't complete statement. Return without moving the caret.
return false;
}
if (TryGetCaretPositionToMove(statementNode, caret, isInsideDelimiters, out var targetPosition)
&& targetPosition != originalCaret)
{
if (speculative)
{
// Return an indication that moving the caret is required, but don't actually move it
return true;
}
Logger.Log(FunctionId.CommandHandler_CompleteStatement, KeyValueLogMessage.Create(LogType.UserAction, m =>
{
m[nameof(isInsideDelimiters)] = isInsideDelimiters;
m[nameof(statementNode)] = statementNode.Kind();
}));
return args.TextView.TryMoveCaretToAndEnsureVisible(targetPosition);
}
return false;
}
private static bool TryGetCaretPositionToMove(SyntaxNode statementNode, SnapshotPoint caret, bool isInsideDelimiters, out SnapshotPoint targetPosition)
{
targetPosition = default;
switch (statementNode.Kind())
{
case SyntaxKind.DoStatement:
// Move caret after the do statement's closing paren.
targetPosition = caret.Snapshot.GetPoint(((DoStatementSyntax)statementNode).CloseParenToken.Span.End);
return true;
case SyntaxKind.ForStatement:
// `For` statements can have semicolon after initializer/declaration or after condition.
// If caret is in initialer/declaration or condition, AND is inside other delimiters, complete statement
// Otherwise, return without moving the caret.
return isInsideDelimiters && TryGetForStatementCaret(caret, (ForStatementSyntax)statementNode, out targetPosition);
case SyntaxKind.ExpressionStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.LocalDeclarationStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.ArrowExpressionClause:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
// These statement types end in a semicolon.
// if the original caret was inside any delimiters, `caret` will be after the outermost delimiter
targetPosition = caret;
return isInsideDelimiters;
default:
// For all other statement types, don't complete statement. Return without moving the caret.
return false;
}
}
private static bool TryGetForStatementCaret(SnapshotPoint originalCaret, ForStatementSyntax forStatement, out SnapshotPoint forStatementCaret)
{
if (CaretIsInForStatementCondition(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Condition.Span.End);
}
else if (CaretIsInForStatementDeclaration(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Declaration.Span.End);
}
else if (CaretIsInForStatementInitializers(originalCaret, forStatement))
{
forStatementCaret = GetCaretAtPosition(forStatement.Initializers.Span.End);
}
else
{
// set caret to default, we will return false
forStatementCaret = default;
}
return (forStatementCaret != default);
// Locals
SnapshotPoint GetCaretAtPosition(int position) => originalCaret.Snapshot.GetPoint(position);
}
private static bool CaretIsInForStatementCondition(int caretPosition, ForStatementSyntax forStatementSyntax)
// If condition is null and caret is in the condition section, as in `for ( ; $$; )`,
// we will have bailed earlier due to not being inside supported delimiters
=> forStatementSyntax.Condition == null
? false
: caretPosition > forStatementSyntax.Condition.SpanStart &&
caretPosition <= forStatementSyntax.Condition.Span.End;
private static bool CaretIsInForStatementDeclaration(int caretPosition, ForStatementSyntax forStatementSyntax)
=> forStatementSyntax.Declaration != null &&
caretPosition > forStatementSyntax.Declaration.Span.Start &&
caretPosition <= forStatementSyntax.Declaration.Span.End;
private static bool CaretIsInForStatementInitializers(int caretPosition, ForStatementSyntax forStatementSyntax)
=> forStatementSyntax.Initializers.Count != 0 &&
caretPosition > forStatementSyntax.Initializers.Span.Start &&
caretPosition <= forStatementSyntax.Initializers.Span.End;
private static bool IsInAStringOrCharacter(SyntaxNode currentNode, SnapshotPoint caret)
// Check to see if caret is before or after string
=> currentNode.IsKind(SyntaxKind.InterpolatedStringExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression)
&& caret.Position < currentNode.Span.End
&& caret.Position > currentNode.SpanStart;
/// <summary>
/// Determines if a statement ends with a closing delimiter, and that closing delimiter exists.
/// </summary>
/// <remarks>
/// <para>Statements such as <c>do { } while (expression);</c> contain embedded enclosing delimiters immediately
/// preceding the semicolon. These delimiters are not part of the expression, but they behave like an argument
/// list for the purposes of identifying relevant places for statement completion:</para>
/// <list type="bullet">
/// <item><description>The closing delimiter is typically inserted by the Automatic Brace Completion feature.</description></item>
/// <item><description>It is not syntactically valid to place a semicolon <em>directly</em> within the delimiters.</description></item>
/// </list>
/// </remarks>
/// <param name="currentNode"></param>
/// <returns><see langword="true"/> if <paramref name="currentNode"/> is a statement that ends with a closing
/// delimiter, and that closing delimiter exists in the source code; otherwise, <see langword="false"/>.
/// </returns>
private static bool StatementClosingDelimiterIsMissing(SyntaxNode currentNode)
{
switch (currentNode.Kind())
{
case SyntaxKind.DoStatement:
var dostatement = (DoStatementSyntax)currentNode;
return dostatement.CloseParenToken.IsMissing;
case SyntaxKind.ForStatement:
var forStatement = (ForStatementSyntax)currentNode;
return forStatement.CloseParenToken.IsMissing;
default:
return false;
}
}
/// <summary>
/// Determines if a syntax node includes all required closing delimiters.
/// </summary>
/// <remarks>
/// <para>Some syntax nodes, such as parenthesized expressions, require a matching closing delimiter to end the
/// syntax node. If this node is omitted from the source code, the parser will automatically insert a zero-width
/// "missing" closing delimiter token to produce a valid syntax tree. This method determines if required closing
/// delimiters are present in the original source.</para>
/// </remarks>
/// <param name="currentNode"></param>
/// <returns>
/// <list type="bullet">
/// <item><description><see langword="true"/> if <paramref name="currentNode"/> requires a closing delimiter and the closing delimiter is present in the source (i.e. not missing)</description></item>
/// <item><description><see langword="true"/> if <paramref name="currentNode"/> does not require a closing delimiter</description></item>
/// <item><description>otherwise, <see langword="false"/>.</description></item>
/// </list>
/// </returns>
private static bool RequiredDelimiterIsMissing(SyntaxNode currentNode)
{
return currentNode.GetBrackets().closeBracket.IsMissing ||
currentNode.GetParentheses().closeParen.IsMissing;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerAnalysisContext : AnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostSessionStartAnalysisScope _scope;
public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationStartAction(_analyzer, action);
}
public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationAction(_analyzer, action);
}
public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSyntaxTreeAction(_analyzer, action);
}
public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterAdditionalFileAction(_analyzer, action);
}
public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSemanticModelAction(_analyzer, action);
}
public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds);
_scope.RegisterSymbolAction(_analyzer, action, symbolKinds);
}
public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolStartAction(_analyzer, action, symbolKind);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void EnableConcurrentExecution()
{
_scope.EnableConcurrentExecution(_analyzer);
}
public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode)
{
_scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode);
}
}
/// <summary>
/// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostCompilationStartAnalysisScope _scope;
private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory;
public AnalyzerCompilationStartAnalysisContext(
DiagnosticAnalyzer analyzer,
HostCompilationStartAnalysisScope scope,
Compilation compilation,
AnalyzerOptions options,
CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory,
CancellationToken cancellationToken)
: base(compilation, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
_compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory;
}
public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationEndAction(_analyzer, action);
}
public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSyntaxTreeAction(_analyzer, action);
}
public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterAdditionalFileAction(_analyzer, action);
}
public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSemanticModelAction(_analyzer, action);
}
public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds);
_scope.RegisterSymbolAction(_analyzer, action, symbolKinds);
}
public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolStartAction(_analyzer, action, symbolKind);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value)
{
var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider);
return compilationAnalysisValueProvider.TryGetValue(key, out value);
}
}
/// <summary>
/// Scope for setting up analyzers for code within a symbol and its members.
/// </summary>
internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostSymbolStartAnalysisScope _scope;
internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostSymbolStartAnalysisScope scope,
ISymbol owningSymbol,
Compilation compilation,
AnalyzerOptions options,
CancellationToken cancellationToken)
: base(owningSymbol, compilation, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolEndAction(_analyzer, action);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for a code block, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope;
internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope,
SyntaxNode codeBlock,
ISymbol owningSymbol,
SemanticModel semanticModel,
AnalyzerOptions options,
CancellationToken cancellationToken)
: base(codeBlock, owningSymbol, semanticModel, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockEndAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostOperationBlockStartAnalysisScope _scope;
internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostOperationBlockStartAnalysisScope scope,
ImmutableArray<IOperation> operationBlocks,
ISymbol owningSymbol,
Compilation compilation,
AnalyzerOptions options,
Func<IOperation, ControlFlowGraph> getControlFlowGraph,
CancellationToken cancellationToken)
: base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockEndAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for an entire session, capable of retrieving the actions.
/// </summary>
internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope
{
private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty;
private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>();
public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer)
{
return _concurrentAnalyzers.Contains(analyzer);
}
public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer)
{
GeneratedCodeAnalysisFlags mode;
return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags;
}
public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action)
{
CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction);
}
public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer)
{
_concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer);
GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution();
}
public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode)
{
_generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode);
}
}
/// <summary>
/// Scope for setting up analyzers for a compilation, capable of retrieving the actions.
/// </summary>
internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope
{
private readonly HostSessionStartAnalysisScope _sessionScope;
public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope)
{
_sessionScope = sessionScope;
}
public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer)
{
AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer);
AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer);
if (sessionActions.IsEmpty)
{
return compilationActions;
}
if (compilationActions.IsEmpty)
{
return sessionActions;
}
return compilationActions.Append(in sessionActions);
}
}
/// <summary>
/// Scope for setting up analyzers for analyzing a symbol and its members.
/// </summary>
internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope
{
public HostSymbolStartAnalysisScope()
{
}
}
/// <summary>
/// Scope for setting up analyzers for a code block, capable of retrieving the actions.
/// </summary>
internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions
{
get { return _codeBlockEndActions; }
}
public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions
{
get { return _syntaxNodeActions; }
}
internal HostCodeBlockStartAnalysisScope()
{
}
public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
_codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer));
}
public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
_syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer));
}
}
internal sealed class HostOperationBlockStartAnalysisScope
{
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions;
public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions;
internal HostOperationBlockStartAnalysisScope()
{
}
public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
_operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer));
}
public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
_operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer));
}
}
internal abstract class HostAnalysisScope
{
private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>();
public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer)
{
return this.GetOrCreateAnalyzerActions(analyzer).Value;
}
public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action)
{
CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction);
}
public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action)
{
CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction);
}
public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action)
{
SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction);
}
public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action)
{
SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction);
}
public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action)
{
var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction);
}
public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction);
// The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler
// does not make CompilationEvents for them. As a workaround, handle them specially by
// registering further SymbolActions (for Methods) and utilize the results to construct
// the necessary SymbolAnalysisContexts.
if (symbolKinds.Contains(SymbolKind.Parameter))
{
RegisterSymbolAction(
analyzer,
context =>
{
ImmutableArray<IParameterSymbol> parameters;
switch (context.Symbol.Kind)
{
case SymbolKind.Method:
parameters = ((IMethodSymbol)context.Symbol).Parameters;
break;
case SymbolKind.Property:
parameters = ((IPropertySymbol)context.Symbol).Parameters;
break;
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)context.Symbol;
var delegateInvokeMethod = namedType.DelegateInvokeMethod;
parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>();
break;
default:
throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context));
}
foreach (var parameter in parameters)
{
if (!parameter.IsImplicitlyDeclared)
{
action(new SymbolAnalysisContext(
parameter,
context.Compilation,
context.Options,
context.ReportDiagnostic,
context.IsSupportedDiagnostic,
context.CancellationToken));
}
}
},
ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType));
}
}
public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction);
}
public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action)
{
var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction);
}
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct
{
CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction);
}
public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction);
}
public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction);
}
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct
{
SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction);
}
public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action)
{
OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction);
}
public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction);
}
public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction);
}
public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction);
}
protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer)
{
return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty));
}
}
/// <summary>
/// Actions registered by a particular analyzer.
/// </summary>
// ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver
// moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking
// if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also,
// the driver needs to apply all relevant actions rather then applying the actions of individual analyzers.
internal struct AnalyzerActions
{
public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false);
private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions;
private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions;
private ImmutableArray<CompilationAnalyzerAction> _compilationActions;
private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions;
private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions;
private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions;
private ImmutableArray<SymbolAnalyzerAction> _symbolActions;
private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions;
private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions;
private ImmutableArray<AnalyzerAction> _codeBlockStartActions;
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions;
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions;
private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions;
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions;
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions;
private ImmutableArray<AnalyzerAction> _syntaxNodeActions;
private ImmutableArray<OperationAnalyzerAction> _operationActions;
private bool _concurrent;
internal AnalyzerActions(bool concurrent)
{
_compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty;
_compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty;
_compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty;
_syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty;
_additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty;
_semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty;
_symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty;
_symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty;
_symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty;
_codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty;
_codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
_codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
_operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty;
_operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
_operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
_syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty;
_operationActions = ImmutableArray<OperationAnalyzerAction>.Empty;
_concurrent = concurrent;
IsEmpty = true;
}
public AnalyzerActions(
ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions,
ImmutableArray<CompilationAnalyzerAction> compilationEndActions,
ImmutableArray<CompilationAnalyzerAction> compilationActions,
ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions,
ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions,
ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions,
ImmutableArray<SymbolAnalyzerAction> symbolActions,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions,
ImmutableArray<AnalyzerAction> codeBlockStartActions,
ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions,
ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions,
ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions,
ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions,
ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions,
ImmutableArray<AnalyzerAction> syntaxNodeActions,
ImmutableArray<OperationAnalyzerAction> operationActions,
bool concurrent,
bool isEmpty)
{
_compilationStartActions = compilationStartActions;
_compilationEndActions = compilationEndActions;
_compilationActions = compilationActions;
_syntaxTreeActions = syntaxTreeActions;
_additionalFileActions = additionalFileActions;
_semanticModelActions = semanticModelActions;
_symbolActions = symbolActions;
_symbolStartActions = symbolStartActions;
_symbolEndActions = symbolEndActions;
_codeBlockStartActions = codeBlockStartActions;
_codeBlockEndActions = codeBlockEndActions;
_codeBlockActions = codeBlockActions;
_operationBlockStartActions = operationBlockStartActions;
_operationBlockEndActions = operationBlockEndActions;
_operationBlockActions = operationBlockActions;
_syntaxNodeActions = syntaxNodeActions;
_operationActions = operationActions;
_concurrent = concurrent;
IsEmpty = isEmpty;
}
public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } }
public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } }
public readonly int CompilationActionsCount { get { return _compilationActions.Length; } }
public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } }
public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } }
public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } }
public readonly int SymbolActionsCount { get { return _symbolActions.Length; } }
public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } }
public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } }
public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } }
public readonly int OperationActionsCount { get { return _operationActions.Length; } }
public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } }
public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } }
public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } }
public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } }
public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } }
public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } }
public readonly bool Concurrent => _concurrent;
public bool IsEmpty { readonly get; private set; }
public readonly bool IsDefault => _compilationStartActions.IsDefault;
internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions
{
get { return _compilationStartActions; }
}
internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions
{
get { return _compilationEndActions; }
}
internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions
{
get { return _compilationActions; }
}
internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions
{
get { return _syntaxTreeActions; }
}
internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions
{
get { return _additionalFileActions; }
}
internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions
{
get { return _semanticModelActions; }
}
internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions
{
get { return _symbolActions; }
}
internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions
{
get { return _symbolStartActions; }
}
internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions
{
get { return _symbolEndActions; }
}
internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions
{
get { return _codeBlockEndActions; }
}
internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions
{
get { return _codeBlockActions; }
}
internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct
{
return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray();
}
internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct
{
return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray();
}
internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct
{
var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance();
foreach (var action in _syntaxNodeActions)
{
if (action.Analyzer == analyzer &&
action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction)
{
builder.Add(syntaxNodeAction);
}
}
return builder.ToImmutableAndFree();
}
internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions
{
get { return _operationBlockActions; }
}
internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions
{
get { return _operationBlockEndActions; }
}
internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions
{
get { return _operationBlockStartActions; }
}
internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions
{
get { return _operationActions; }
}
internal void AddCompilationStartAction(CompilationStartAnalyzerAction action)
{
_compilationStartActions = _compilationStartActions.Add(action);
IsEmpty = false;
}
internal void AddCompilationEndAction(CompilationAnalyzerAction action)
{
_compilationEndActions = _compilationEndActions.Add(action);
IsEmpty = false;
}
internal void AddCompilationAction(CompilationAnalyzerAction action)
{
_compilationActions = _compilationActions.Add(action);
IsEmpty = false;
}
internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action)
{
_syntaxTreeActions = _syntaxTreeActions.Add(action);
IsEmpty = false;
}
internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action)
{
_additionalFileActions = _additionalFileActions.Add(action);
IsEmpty = false;
}
internal void AddSemanticModelAction(SemanticModelAnalyzerAction action)
{
_semanticModelActions = _semanticModelActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolAction(SymbolAnalyzerAction action)
{
_symbolActions = _symbolActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolStartAction(SymbolStartAnalyzerAction action)
{
_symbolStartActions = _symbolStartActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolEndAction(SymbolEndAnalyzerAction action)
{
_symbolEndActions = _symbolEndActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct
{
_codeBlockStartActions = _codeBlockStartActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action)
{
_codeBlockEndActions = _codeBlockEndActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockAction(CodeBlockAnalyzerAction action)
{
_codeBlockActions = _codeBlockActions.Add(action);
IsEmpty = false;
}
internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct
{
_syntaxNodeActions = _syntaxNodeActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action)
{
_operationBlockStartActions = _operationBlockStartActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockAction(OperationBlockAnalyzerAction action)
{
_operationBlockActions = _operationBlockActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action)
{
_operationBlockEndActions = _operationBlockEndActions.Add(action);
IsEmpty = false;
}
internal void AddOperationAction(OperationAnalyzerAction action)
{
_operationActions = _operationActions.Add(action);
IsEmpty = false;
}
internal void EnableConcurrentExecution()
{
_concurrent = true;
}
/// <summary>
/// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance.
/// </summary>
/// <param name="otherActions">Analyzer actions to append</param>.
public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true)
{
if (otherActions.IsDefault)
{
throw new ArgumentNullException(nameof(otherActions));
}
AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent);
actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions);
actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions);
actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions);
actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions);
actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions);
actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions);
actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions);
actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions;
actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions;
actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions);
actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions);
actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions);
actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions);
actions._operationActions = _operationActions.AddRange(otherActions._operationActions);
actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions);
actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions);
actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions);
actions.IsEmpty = IsEmpty && otherActions.IsEmpty;
return actions;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerAnalysisContext : AnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostSessionStartAnalysisScope _scope;
public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationStartAction(_analyzer, action);
}
public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationAction(_analyzer, action);
}
public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSyntaxTreeAction(_analyzer, action);
}
public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterAdditionalFileAction(_analyzer, action);
}
public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSemanticModelAction(_analyzer, action);
}
public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds);
_scope.RegisterSymbolAction(_analyzer, action, symbolKinds);
}
public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolStartAction(_analyzer, action, symbolKind);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void EnableConcurrentExecution()
{
_scope.EnableConcurrentExecution(_analyzer);
}
public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode)
{
_scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode);
}
}
/// <summary>
/// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostCompilationStartAnalysisScope _scope;
private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory;
public AnalyzerCompilationStartAnalysisContext(
DiagnosticAnalyzer analyzer,
HostCompilationStartAnalysisScope scope,
Compilation compilation,
AnalyzerOptions options,
CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory,
CancellationToken cancellationToken)
: base(compilation, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
_compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory;
}
public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCompilationEndAction(_analyzer, action);
}
public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSyntaxTreeAction(_analyzer, action);
}
public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterAdditionalFileAction(_analyzer, action);
}
public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSemanticModelAction(_analyzer, action);
}
public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds);
_scope.RegisterSymbolAction(_analyzer, action, symbolKinds);
}
public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolStartAction(_analyzer, action, symbolKind);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value)
{
var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider);
return compilationAnalysisValueProvider.TryGetValue(key, out value);
}
}
/// <summary>
/// Scope for setting up analyzers for code within a symbol and its members.
/// </summary>
internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostSymbolStartAnalysisScope _scope;
internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostSymbolStartAnalysisScope scope,
ISymbol owningSymbol,
Compilation compilation,
AnalyzerOptions options,
CancellationToken cancellationToken)
: base(owningSymbol, compilation, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterSymbolEndAction(_analyzer, action);
}
public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action);
}
public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockStartAction(_analyzer, action);
}
public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for a code block, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope;
internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope,
SyntaxNode codeBlock,
ISymbol owningSymbol,
SemanticModel semanticModel,
AnalyzerOptions options,
CancellationToken cancellationToken)
: base(codeBlock, owningSymbol, semanticModel, options, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterCodeBlockEndAction(_analyzer, action);
}
public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds);
_scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers.
/// </summary>
internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext
{
private readonly DiagnosticAnalyzer _analyzer;
private readonly HostOperationBlockStartAnalysisScope _scope;
internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer,
HostOperationBlockStartAnalysisScope scope,
ImmutableArray<IOperation> operationBlocks,
ISymbol owningSymbol,
Compilation compilation,
AnalyzerOptions options,
Func<IOperation, ControlFlowGraph> getControlFlowGraph,
CancellationToken cancellationToken)
: base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken)
{
_analyzer = analyzer;
_scope = scope;
}
public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action);
_scope.RegisterOperationBlockEndAction(_analyzer, action);
}
public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds);
_scope.RegisterOperationAction(_analyzer, action, operationKinds);
}
}
/// <summary>
/// Scope for setting up analyzers for an entire session, capable of retrieving the actions.
/// </summary>
internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope
{
private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty;
private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>();
public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer)
{
return _concurrentAnalyzers.Contains(analyzer);
}
public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer)
{
GeneratedCodeAnalysisFlags mode;
return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags;
}
public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action)
{
CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction);
}
public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer)
{
_concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer);
GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution();
}
public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode)
{
_generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode);
}
}
/// <summary>
/// Scope for setting up analyzers for a compilation, capable of retrieving the actions.
/// </summary>
internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope
{
private readonly HostSessionStartAnalysisScope _sessionScope;
public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope)
{
_sessionScope = sessionScope;
}
public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer)
{
AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer);
AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer);
if (sessionActions.IsEmpty)
{
return compilationActions;
}
if (compilationActions.IsEmpty)
{
return sessionActions;
}
return compilationActions.Append(in sessionActions);
}
}
/// <summary>
/// Scope for setting up analyzers for analyzing a symbol and its members.
/// </summary>
internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope
{
public HostSymbolStartAnalysisScope()
{
}
}
/// <summary>
/// Scope for setting up analyzers for a code block, capable of retrieving the actions.
/// </summary>
internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions
{
get { return _codeBlockEndActions; }
}
public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions
{
get { return _syntaxNodeActions; }
}
internal HostCodeBlockStartAnalysisScope()
{
}
public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
_codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer));
}
public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds)
{
_syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer));
}
}
internal sealed class HostOperationBlockStartAnalysisScope
{
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions;
public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions;
internal HostOperationBlockStartAnalysisScope()
{
}
public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
_operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer));
}
public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
_operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer));
}
}
internal abstract class HostAnalysisScope
{
private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>();
public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer)
{
return this.GetOrCreateAnalyzerActions(analyzer).Value;
}
public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action)
{
CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction);
}
public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action)
{
CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction);
}
public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action)
{
SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction);
}
public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action)
{
SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction);
}
public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action)
{
var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction);
}
public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds)
{
SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction);
// The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler
// does not make CompilationEvents for them. As a workaround, handle them specially by
// registering further SymbolActions (for Methods) and utilize the results to construct
// the necessary SymbolAnalysisContexts.
if (symbolKinds.Contains(SymbolKind.Parameter))
{
RegisterSymbolAction(
analyzer,
context =>
{
ImmutableArray<IParameterSymbol> parameters;
switch (context.Symbol.Kind)
{
case SymbolKind.Method:
parameters = ((IMethodSymbol)context.Symbol).Parameters;
break;
case SymbolKind.Property:
parameters = ((IPropertySymbol)context.Symbol).Parameters;
break;
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)context.Symbol;
var delegateInvokeMethod = namedType.DelegateInvokeMethod;
parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>();
break;
default:
throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context));
}
foreach (var parameter in parameters)
{
if (!parameter.IsImplicitlyDeclared)
{
action(new SymbolAnalysisContext(
parameter,
context.Compilation,
context.Options,
context.ReportDiagnostic,
context.IsSupportedDiagnostic,
context.CancellationToken));
}
}
},
ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType));
}
}
public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind)
{
var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction);
}
public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action)
{
var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction);
}
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct
{
CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction);
}
public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction);
}
public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action)
{
CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction);
}
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct
{
SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction);
}
public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action)
{
OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction);
}
public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction);
}
public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action)
{
OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction);
}
public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds)
{
OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer);
this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction);
}
protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer)
{
return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty));
}
}
/// <summary>
/// Actions registered by a particular analyzer.
/// </summary>
// ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver
// moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking
// if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also,
// the driver needs to apply all relevant actions rather then applying the actions of individual analyzers.
internal struct AnalyzerActions
{
public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false);
private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions;
private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions;
private ImmutableArray<CompilationAnalyzerAction> _compilationActions;
private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions;
private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions;
private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions;
private ImmutableArray<SymbolAnalyzerAction> _symbolActions;
private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions;
private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions;
private ImmutableArray<AnalyzerAction> _codeBlockStartActions;
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions;
private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions;
private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions;
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions;
private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions;
private ImmutableArray<AnalyzerAction> _syntaxNodeActions;
private ImmutableArray<OperationAnalyzerAction> _operationActions;
private bool _concurrent;
internal AnalyzerActions(bool concurrent)
{
_compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty;
_compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty;
_compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty;
_syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty;
_additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty;
_semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty;
_symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty;
_symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty;
_symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty;
_codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty;
_codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
_codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty;
_operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty;
_operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
_operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty;
_syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty;
_operationActions = ImmutableArray<OperationAnalyzerAction>.Empty;
_concurrent = concurrent;
IsEmpty = true;
}
public AnalyzerActions(
ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions,
ImmutableArray<CompilationAnalyzerAction> compilationEndActions,
ImmutableArray<CompilationAnalyzerAction> compilationActions,
ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions,
ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions,
ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions,
ImmutableArray<SymbolAnalyzerAction> symbolActions,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions,
ImmutableArray<AnalyzerAction> codeBlockStartActions,
ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions,
ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions,
ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions,
ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions,
ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions,
ImmutableArray<AnalyzerAction> syntaxNodeActions,
ImmutableArray<OperationAnalyzerAction> operationActions,
bool concurrent,
bool isEmpty)
{
_compilationStartActions = compilationStartActions;
_compilationEndActions = compilationEndActions;
_compilationActions = compilationActions;
_syntaxTreeActions = syntaxTreeActions;
_additionalFileActions = additionalFileActions;
_semanticModelActions = semanticModelActions;
_symbolActions = symbolActions;
_symbolStartActions = symbolStartActions;
_symbolEndActions = symbolEndActions;
_codeBlockStartActions = codeBlockStartActions;
_codeBlockEndActions = codeBlockEndActions;
_codeBlockActions = codeBlockActions;
_operationBlockStartActions = operationBlockStartActions;
_operationBlockEndActions = operationBlockEndActions;
_operationBlockActions = operationBlockActions;
_syntaxNodeActions = syntaxNodeActions;
_operationActions = operationActions;
_concurrent = concurrent;
IsEmpty = isEmpty;
}
public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } }
public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } }
public readonly int CompilationActionsCount { get { return _compilationActions.Length; } }
public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } }
public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } }
public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } }
public readonly int SymbolActionsCount { get { return _symbolActions.Length; } }
public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } }
public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } }
public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } }
public readonly int OperationActionsCount { get { return _operationActions.Length; } }
public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } }
public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } }
public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } }
public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } }
public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } }
public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } }
public readonly bool Concurrent => _concurrent;
public bool IsEmpty { readonly get; private set; }
public readonly bool IsDefault => _compilationStartActions.IsDefault;
internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions
{
get { return _compilationStartActions; }
}
internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions
{
get { return _compilationEndActions; }
}
internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions
{
get { return _compilationActions; }
}
internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions
{
get { return _syntaxTreeActions; }
}
internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions
{
get { return _additionalFileActions; }
}
internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions
{
get { return _semanticModelActions; }
}
internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions
{
get { return _symbolActions; }
}
internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions
{
get { return _symbolStartActions; }
}
internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions
{
get { return _symbolEndActions; }
}
internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions
{
get { return _codeBlockEndActions; }
}
internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions
{
get { return _codeBlockActions; }
}
internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct
{
return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray();
}
internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct
{
return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray();
}
internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct
{
var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance();
foreach (var action in _syntaxNodeActions)
{
if (action.Analyzer == analyzer &&
action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction)
{
builder.Add(syntaxNodeAction);
}
}
return builder.ToImmutableAndFree();
}
internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions
{
get { return _operationBlockActions; }
}
internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions
{
get { return _operationBlockEndActions; }
}
internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions
{
get { return _operationBlockStartActions; }
}
internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions
{
get { return _operationActions; }
}
internal void AddCompilationStartAction(CompilationStartAnalyzerAction action)
{
_compilationStartActions = _compilationStartActions.Add(action);
IsEmpty = false;
}
internal void AddCompilationEndAction(CompilationAnalyzerAction action)
{
_compilationEndActions = _compilationEndActions.Add(action);
IsEmpty = false;
}
internal void AddCompilationAction(CompilationAnalyzerAction action)
{
_compilationActions = _compilationActions.Add(action);
IsEmpty = false;
}
internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action)
{
_syntaxTreeActions = _syntaxTreeActions.Add(action);
IsEmpty = false;
}
internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action)
{
_additionalFileActions = _additionalFileActions.Add(action);
IsEmpty = false;
}
internal void AddSemanticModelAction(SemanticModelAnalyzerAction action)
{
_semanticModelActions = _semanticModelActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolAction(SymbolAnalyzerAction action)
{
_symbolActions = _symbolActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolStartAction(SymbolStartAnalyzerAction action)
{
_symbolStartActions = _symbolStartActions.Add(action);
IsEmpty = false;
}
internal void AddSymbolEndAction(SymbolEndAnalyzerAction action)
{
_symbolEndActions = _symbolEndActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct
{
_codeBlockStartActions = _codeBlockStartActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action)
{
_codeBlockEndActions = _codeBlockEndActions.Add(action);
IsEmpty = false;
}
internal void AddCodeBlockAction(CodeBlockAnalyzerAction action)
{
_codeBlockActions = _codeBlockActions.Add(action);
IsEmpty = false;
}
internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct
{
_syntaxNodeActions = _syntaxNodeActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action)
{
_operationBlockStartActions = _operationBlockStartActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockAction(OperationBlockAnalyzerAction action)
{
_operationBlockActions = _operationBlockActions.Add(action);
IsEmpty = false;
}
internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action)
{
_operationBlockEndActions = _operationBlockEndActions.Add(action);
IsEmpty = false;
}
internal void AddOperationAction(OperationAnalyzerAction action)
{
_operationActions = _operationActions.Add(action);
IsEmpty = false;
}
internal void EnableConcurrentExecution()
{
_concurrent = true;
}
/// <summary>
/// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance.
/// </summary>
/// <param name="otherActions">Analyzer actions to append</param>.
public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true)
{
if (otherActions.IsDefault)
{
throw new ArgumentNullException(nameof(otherActions));
}
AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent);
actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions);
actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions);
actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions);
actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions);
actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions);
actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions);
actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions);
actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions;
actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions;
actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions);
actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions);
actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions);
actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions);
actions._operationActions = _operationActions.AddRange(otherActions._operationActions);
actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions);
actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions);
actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions);
actions.IsEmpty = IsEmpty && otherActions.IsEmpty;
return actions;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase
{
[Fact]
public void AreSatisfied()
{
var moduleVersionId = Guid.NewGuid();
const int methodToken = 0x06000001;
const int methodVersion = 1;
const uint startOffset = 1;
const uint endOffsetExclusive = 3;
var constraints = new MethodContextReuseConstraints(
moduleVersionId,
methodToken,
methodVersion,
new ILSpan(startOffset, endOffsetExclusive));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive));
}
[Fact]
public void EndExclusive()
{
var spans = new[]
{
new ILSpan(0u, uint.MaxValue),
new ILSpan(1, 9),
new ILSpan(2, 8),
new ILSpan(1, 3),
new ILSpan(7, 9),
};
Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1)));
Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2)));
Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3)));
Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4)));
Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5)));
}
[Fact]
public void Cumulative()
{
var span = ILSpan.MaxValue;
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]);
Assert.Equal(new ILSpan(0u, uint.MaxValue), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) });
Assert.Equal(new ILSpan(1, 10), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) });
Assert.Equal(new ILSpan(2, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) });
Assert.Equal(new ILSpan(3, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) });
Assert.Equal(new ILSpan(3, 7), span);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase
{
[Fact]
public void AreSatisfied()
{
var moduleVersionId = Guid.NewGuid();
const int methodToken = 0x06000001;
const int methodVersion = 1;
const uint startOffset = 1;
const uint endOffsetExclusive = 3;
var constraints = new MethodContextReuseConstraints(
moduleVersionId,
methodToken,
methodVersion,
new ILSpan(startOffset, endOffsetExclusive));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive));
}
[Fact]
public void EndExclusive()
{
var spans = new[]
{
new ILSpan(0u, uint.MaxValue),
new ILSpan(1, 9),
new ILSpan(2, 8),
new ILSpan(1, 3),
new ILSpan(7, 9),
};
Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1)));
Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2)));
Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3)));
Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4)));
Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5)));
}
[Fact]
public void Cumulative()
{
var span = ILSpan.MaxValue;
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]);
Assert.Equal(new ILSpan(0u, uint.MaxValue), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) });
Assert.Equal(new ILSpan(1, 10), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) });
Assert.Equal(new ILSpan(2, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) });
Assert.Equal(new ILSpan(3, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) });
Assert.Equal(new ILSpan(3, 7), span);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/UsingBlockHighlighter.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.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class UsingBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)()
If usingBlock Is Nothing Then
Return
End If
With usingBlock
highlights.Add(.UsingStatement.UsingKeyword.Span)
highlights.Add(.EndUsingStatement.Span)
End With
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.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class UsingBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)()
If usingBlock Is Nothing Then
Return
End If
With usingBlock
highlights.Add(.UsingStatement.UsingKeyword.Span)
highlights.Add(.EndUsingStatement.Span)
End With
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenImplicitlyTypeArraysTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.IO;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenImplicitlyTypeArraysTests : CompilingTestBase
{
#region "Functionality tests"
[Fact]
public void Test_001_Simple()
{
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, 2, 3};
System.Console.Write(a.SequenceEqual(new int[]{1, 2, 3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_002_IntTypeBest()
{
// Best type: int
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, (byte)2, (short)3};
System.Console.Write(a.SequenceEqual(new int[]{1, (byte)2, (short)3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_003_DoubleTypeBest()
{
// Best type: double
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d};
System.Console.Write(a.SequenceEqual(new double[]{(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact, WorkItem(895655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895655")]
public void Test_004_Enum()
{
// Enums conversions
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
enum E
{
START
};
public static void Main()
{
var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
}
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended);
comp.VerifyDiagnostics(
// (15,54): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 54),
// (15,88): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 88),
// (15,93): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 93),
// (17,84): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 84),
// (17,118): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 118),
// (17,123): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 123),
// (15,21): error CS0826: No best type found for implicitly-typed array
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}").WithLocation(15, 21),
// (17,35): error CS1929: '?[]' does not contain a definition for 'SequenceEqual' and the best extension method overload 'System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)' requires a receiver of type 'System.Linq.IQueryable<Test.Program.E>'
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("?[]", "SequenceEqual", "System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)", "System.Linq.IQueryable<Test.Program.E>").WithLocation(17, 35)
);
}
[Fact]
public void Test_005_ObjectTypeBest()
{
// Implicit reference conversions -- From any reference-type to object.
var source = @"
using System.Linq;
namespace Test
{
public class C { };
public interface I { };
public class C2 : I { };
public class Program
{
delegate void D();
public static void M() { }
public static void Main()
{
object o = new object();
C c = new C();
I i = new C2();
D d = new D(M);
int[] aa = new int[] {1};
var a = new [] {o, """", c, i, d, aa};
System.Console.Write(a.SequenceEqual(new object[]{o, """", c, i, d, aa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_006_ArrayTypeBest()
{
// Implicit reference conversions -- From an array-type S with an element type SE to an array-type T with an element type TE,
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
object[] oa = new object[] {null};
string[] sa = new string[] {null};
var a = new [] {oa, sa};
System.Console.Write(a.SequenceEqual(new object[][]{oa, sa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_007A()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>.
var testSrc = @"
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] ia = new int[] {1, 2, 3};
IList<int> la = new List<int> {1, 2, 3};
var a = new [] {ia, la};
System.Console.Write(a.SequenceEqual(new IList<int>[]{ia, la}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_007B()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IReadOnlyList<S>.
var testSrc = @"
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] array = new int[] {1, 2, 3};
object obj = array;
IEnumerable<int> ro1 = array;
IReadOnlyList<int> ro2 = (IReadOnlyList<int>)obj;
IReadOnlyList<int> ro3 = (IReadOnlyList<int>)array;
IReadOnlyList<int> ro4 = obj as IReadOnlyList<int>;
System.Console.WriteLine(ro4 != null ? 1 : 2);
}
}
}
";
var mscorlib17626 = MetadataReference.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
CompileAndVerify(testSrc, new MetadataReference[] { mscorlib17626 }, expectedOutput: "1", targetFramework: TargetFramework.Empty);
}
[Fact]
public void Test_008_DelegateType()
{
// Implicit reference conversions -- From any delegate-type to System.Delegate.
var source = @"
using System;
using System.Linq;
namespace Test
{
public class Program
{
delegate void D1();
public static void M1() {}
delegate int D2();
public static int M2() { return 0;}
delegate void D3(int i);
public static void M3(int i) {}
delegate void D4(params object[] o);
public static void M4(params object[] o) { }
public static void Main()
{
D1 d1 = new D1(M1);
D2 d2 = new D2(M2);
D3 d3 = new D3(M3);
D4 d4 = new D4(M4);
Delegate d = d1;
var a = new [] {d, d1, d2, d3, d4};
System.Console.Write(a.SequenceEqual(new Delegate[]{d, d1, d2, d3, d4}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_009_Null()
{
// Implicit reference conversions -- From the null type to any reference-type.
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {""aa"", ""bb"", null};
System.Console.Write(a.SequenceEqual(new string[]{""aa"", ""bb"", null}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_010_TypeParameter()
{
// Implicit reference conversions --
// For a type-parameter T that is known to be a reference type , the following
// implicit reference conversions exist:
// From T to its effective base class C, from T to any base class of C,
// and from T to any interface implemented by C.
var source = @"
using System.Linq;
namespace Test
{
public interface I {}
public class B {}
public class C : B, I {}
public class D : C {}
public class Program
{
public static void M<T>() where T : C, new()
{
T t = new T();
I i = t;
var a = new [] {i, t};
System.Console.Write(a.SequenceEqual(new I[]{i, t}));
}
public static void Main()
{
M<D>();
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_011_BoxingConversion()
{
// Implicit reference conversions -- Boxing conversions
var testSrc = @"
using System;
using System.Linq;
namespace Test
{
public struct S
{
}
public class Program
{
enum E { START };
public static void Main()
{
IComparable v = 1;
int? i = 1;
var a = new [] {v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13};
System.Console.Write(a.SequenceEqual(new IComparable[]{v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_012_UserDefinedImplicitConversion()
{
// User-defined implicit conversions.
var testSrc = @"
using System.Linq;
namespace Test
{
public class B {}
public class C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
B b = new B();
C c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
// NYI: When user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_013_A_UserDefinedNullableConversions()
{
// Lifted user-defined conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public struct B { }
public struct C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
C? c = new C();
B? b = new B();
if (!(new [] {b, c}.SequenceEqual(new B?[] {b, c})))
{
System.Console.WriteLine(""Test fail at struct C? implicitly convert to struct B?"");
}
}
}
}
";
// NYI: When lifted user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
// Bug 10700: We should be able to infer the array type from elements of types int? and short?
[Fact]
public void Test_013_B_NullableConversions()
{
// Lifted implicit numeric conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
int? i = 1;
short? s = 2;
if (!new [] {i, s}.SequenceEqual(new int?[] {i, s}))
{
System.Console.WriteLine(""Test fail at short? implicitly convert to int?"");
}
}
}
}
";
// NYI: When lifted conversions are implemented, remove the diagnostics check
// NYI: and replace it with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_014_LambdaExpression()
{
// Implicitly conversion from lambda expression to compatible delegate type
var source = @"
using System;
namespace Test
{
public class Program
{
delegate int D(int i);
public static int M(int i) {return i;}
public static void Main()
{
var a = new [] {new D(M), (int i)=>{return i;}, x => x+1, (int i)=>{short s = 2; return s;}};
Console.Write(((a is D[]) && (a.Length==4)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_015_ImplicitlyTypedLocalExpr()
{
// local variable declared as "var" type is used inside an implicitly typed array.
var source = @"
using System.Linq;
namespace Test
{
public class B { };
public class C : B { };
public class Program
{
public static void Main()
{
var b = new B();
var c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_016_ArrayCreationExpression()
{
// Array creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new int[1] , new int[3] {11, 12, 13}, new int[] {21, 22, 23}};
Console.Write(((a is int[][]) && (a.Length==3)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_017_AnonymousObjectCreationExpression()
{
// Anonymous object creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new {i = 2, s = ""bb""}, new {i = 3, s = ""cc""}};
Console.Write(((a is Array) && (a.Length==2)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_018_MemberAccessExpression()
{
// Member access expression as element in implicitly typed arrays
var source = @"
using System.Linq;
using NT = Test;
namespace Test
{
public class Program
{
public delegate int D(string s);
public static D d1 = new D(M2);
public static int M<T>(string s) {return 1;}
public static int M2(string s) {return 2;}
public D d2 = new D(M2);
public static Program p = new Program();
public static Program GetP() {return p;}
public static void Main()
{
System.Console.Write(new [] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}.SequenceEqual(
new D[] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_019_JaggedArray()
{
// JaggedArray in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new [] {new [] {1}},
new [] {new int[] {2}},
new int[][] {new int[] {3}},
new int[][] {new [] {4}} };
if ( !((a3 is int[][][]) && (a3.Length == 4)) )
{
Console.Write(""Test fail"");
}
else
{
Console.Write(""True"");
}
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_020_MultiDimensionalArray()
{
// MultiDimensionalArray in implicitly typed arrays
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new int[,,] {{{3, 4}}},
new int[,,] {{{3, 4}}} };
if ( !((a3 is int[][,,]) && (a3.Rank == 1) && (a3.Length == 2)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_021_MultiDimensionalArray_02()
{
// Implicitly typed arrays should can be used in creating MultiDimensionalArray
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [,,] { {{2, 3, 4}}, {{2, 3, 4}} };
if ( !((a3 is int[,,]) && (a3.Rank == 3) && (a3.Length == 6)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}
";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_022_GenericMethod()
{
// Implicitly typed arrays used in generic method
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
System.Console.Write(GM(new [] {1, 2, 3}).SequenceEqual(new int[]{1, 2, 3}));
}
public static T GM<T>(T t)
{
return t;
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Query()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int[] ta = new int[] {1, 2, 3, 4, 5};
IEnumerable i = ta;
IEnumerable[] a = new [] {i, from c in ta select c, from c in ta group c by c,
from c in ta select c into g select g, from c in ta where c==3 select c,
from c in ta orderby c select c, from c in ta orderby c ascending select c,
from c in ta orderby c descending select c, from c in ta where c==3 orderby c select c};
Console.Write((a is IEnumerable[]) && (a.Length==9));
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Literal()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write(new [] {true, false}.SequenceEqual(new bool[] {true, false}));
Console.Write(new [] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}.SequenceEqual(
new ulong[] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}));
Console.Write(new [] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}.SequenceEqual(
new long[] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}));
Console.Write(new [] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}.SequenceEqual(
new ulong[] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}));
Console.Write(new [] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}.SequenceEqual(
new long[] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}));
Console.Write(new [] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D}.SequenceEqual(
new double[] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D})) ;
Console.Write(new [] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}.SequenceEqual(
new decimal[] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}.SequenceEqual(
new double[] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}.SequenceEqual(
new decimal[] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}));
}
}
";
CompileAndVerify(
source,
expectedOutput: "TrueTrueTrueTrueTrueTrueTrueTrueTrue");
}
#endregion
#region "Error tests"
[Fact]
public void Error_NonArrayInitExpr()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "3").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[Fact]
public void Error_NonArrayInitExpr_02()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, x, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0103: The name 'x' does not exist in the current context
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[WorkItem(543571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543571")]
[Fact]
public void CS0826ERR_ImplicitlyTypedArrayNoBestType()
{
var text = @"
using System;
namespace Test
{
public class Program
{
enum E
{
Zero,
FortyTwo = 42
};
public static void Main()
{
E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Console.WriteLine(String.Format(""Type={0}, a[0]={1}, a[1]={2}"", a.GetType(), a[0], a[1]));
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (16,21): error CS0826: No best type found for implicitly-typed array
// E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { E.FortyTwo, 0 }").WithLocation(16, 21));
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.IO;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenImplicitlyTypeArraysTests : CompilingTestBase
{
#region "Functionality tests"
[Fact]
public void Test_001_Simple()
{
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, 2, 3};
System.Console.Write(a.SequenceEqual(new int[]{1, 2, 3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_002_IntTypeBest()
{
// Best type: int
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, (byte)2, (short)3};
System.Console.Write(a.SequenceEqual(new int[]{1, (byte)2, (short)3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_003_DoubleTypeBest()
{
// Best type: double
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d};
System.Console.Write(a.SequenceEqual(new double[]{(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact, WorkItem(895655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895655")]
public void Test_004_Enum()
{
// Enums conversions
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
enum E
{
START
};
public static void Main()
{
var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
}
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended);
comp.VerifyDiagnostics(
// (15,54): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 54),
// (15,88): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 88),
// (15,93): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 93),
// (17,84): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 84),
// (17,118): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 118),
// (17,123): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 123),
// (15,21): error CS0826: No best type found for implicitly-typed array
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}").WithLocation(15, 21),
// (17,35): error CS1929: '?[]' does not contain a definition for 'SequenceEqual' and the best extension method overload 'System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)' requires a receiver of type 'System.Linq.IQueryable<Test.Program.E>'
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("?[]", "SequenceEqual", "System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)", "System.Linq.IQueryable<Test.Program.E>").WithLocation(17, 35)
);
}
[Fact]
public void Test_005_ObjectTypeBest()
{
// Implicit reference conversions -- From any reference-type to object.
var source = @"
using System.Linq;
namespace Test
{
public class C { };
public interface I { };
public class C2 : I { };
public class Program
{
delegate void D();
public static void M() { }
public static void Main()
{
object o = new object();
C c = new C();
I i = new C2();
D d = new D(M);
int[] aa = new int[] {1};
var a = new [] {o, """", c, i, d, aa};
System.Console.Write(a.SequenceEqual(new object[]{o, """", c, i, d, aa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_006_ArrayTypeBest()
{
// Implicit reference conversions -- From an array-type S with an element type SE to an array-type T with an element type TE,
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
object[] oa = new object[] {null};
string[] sa = new string[] {null};
var a = new [] {oa, sa};
System.Console.Write(a.SequenceEqual(new object[][]{oa, sa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_007A()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>.
var testSrc = @"
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] ia = new int[] {1, 2, 3};
IList<int> la = new List<int> {1, 2, 3};
var a = new [] {ia, la};
System.Console.Write(a.SequenceEqual(new IList<int>[]{ia, la}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_007B()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IReadOnlyList<S>.
var testSrc = @"
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] array = new int[] {1, 2, 3};
object obj = array;
IEnumerable<int> ro1 = array;
IReadOnlyList<int> ro2 = (IReadOnlyList<int>)obj;
IReadOnlyList<int> ro3 = (IReadOnlyList<int>)array;
IReadOnlyList<int> ro4 = obj as IReadOnlyList<int>;
System.Console.WriteLine(ro4 != null ? 1 : 2);
}
}
}
";
var mscorlib17626 = MetadataReference.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
CompileAndVerify(testSrc, new MetadataReference[] { mscorlib17626 }, expectedOutput: "1", targetFramework: TargetFramework.Empty);
}
[Fact]
public void Test_008_DelegateType()
{
// Implicit reference conversions -- From any delegate-type to System.Delegate.
var source = @"
using System;
using System.Linq;
namespace Test
{
public class Program
{
delegate void D1();
public static void M1() {}
delegate int D2();
public static int M2() { return 0;}
delegate void D3(int i);
public static void M3(int i) {}
delegate void D4(params object[] o);
public static void M4(params object[] o) { }
public static void Main()
{
D1 d1 = new D1(M1);
D2 d2 = new D2(M2);
D3 d3 = new D3(M3);
D4 d4 = new D4(M4);
Delegate d = d1;
var a = new [] {d, d1, d2, d3, d4};
System.Console.Write(a.SequenceEqual(new Delegate[]{d, d1, d2, d3, d4}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_009_Null()
{
// Implicit reference conversions -- From the null type to any reference-type.
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {""aa"", ""bb"", null};
System.Console.Write(a.SequenceEqual(new string[]{""aa"", ""bb"", null}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_010_TypeParameter()
{
// Implicit reference conversions --
// For a type-parameter T that is known to be a reference type , the following
// implicit reference conversions exist:
// From T to its effective base class C, from T to any base class of C,
// and from T to any interface implemented by C.
var source = @"
using System.Linq;
namespace Test
{
public interface I {}
public class B {}
public class C : B, I {}
public class D : C {}
public class Program
{
public static void M<T>() where T : C, new()
{
T t = new T();
I i = t;
var a = new [] {i, t};
System.Console.Write(a.SequenceEqual(new I[]{i, t}));
}
public static void Main()
{
M<D>();
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_011_BoxingConversion()
{
// Implicit reference conversions -- Boxing conversions
var testSrc = @"
using System;
using System.Linq;
namespace Test
{
public struct S
{
}
public class Program
{
enum E { START };
public static void Main()
{
IComparable v = 1;
int? i = 1;
var a = new [] {v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13};
System.Console.Write(a.SequenceEqual(new IComparable[]{v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_012_UserDefinedImplicitConversion()
{
// User-defined implicit conversions.
var testSrc = @"
using System.Linq;
namespace Test
{
public class B {}
public class C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
B b = new B();
C c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
// NYI: When user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_013_A_UserDefinedNullableConversions()
{
// Lifted user-defined conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public struct B { }
public struct C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
C? c = new C();
B? b = new B();
if (!(new [] {b, c}.SequenceEqual(new B?[] {b, c})))
{
System.Console.WriteLine(""Test fail at struct C? implicitly convert to struct B?"");
}
}
}
}
";
// NYI: When lifted user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
// Bug 10700: We should be able to infer the array type from elements of types int? and short?
[Fact]
public void Test_013_B_NullableConversions()
{
// Lifted implicit numeric conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
int? i = 1;
short? s = 2;
if (!new [] {i, s}.SequenceEqual(new int?[] {i, s}))
{
System.Console.WriteLine(""Test fail at short? implicitly convert to int?"");
}
}
}
}
";
// NYI: When lifted conversions are implemented, remove the diagnostics check
// NYI: and replace it with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_014_LambdaExpression()
{
// Implicitly conversion from lambda expression to compatible delegate type
var source = @"
using System;
namespace Test
{
public class Program
{
delegate int D(int i);
public static int M(int i) {return i;}
public static void Main()
{
var a = new [] {new D(M), (int i)=>{return i;}, x => x+1, (int i)=>{short s = 2; return s;}};
Console.Write(((a is D[]) && (a.Length==4)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_015_ImplicitlyTypedLocalExpr()
{
// local variable declared as "var" type is used inside an implicitly typed array.
var source = @"
using System.Linq;
namespace Test
{
public class B { };
public class C : B { };
public class Program
{
public static void Main()
{
var b = new B();
var c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_016_ArrayCreationExpression()
{
// Array creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new int[1] , new int[3] {11, 12, 13}, new int[] {21, 22, 23}};
Console.Write(((a is int[][]) && (a.Length==3)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_017_AnonymousObjectCreationExpression()
{
// Anonymous object creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new {i = 2, s = ""bb""}, new {i = 3, s = ""cc""}};
Console.Write(((a is Array) && (a.Length==2)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_018_MemberAccessExpression()
{
// Member access expression as element in implicitly typed arrays
var source = @"
using System.Linq;
using NT = Test;
namespace Test
{
public class Program
{
public delegate int D(string s);
public static D d1 = new D(M2);
public static int M<T>(string s) {return 1;}
public static int M2(string s) {return 2;}
public D d2 = new D(M2);
public static Program p = new Program();
public static Program GetP() {return p;}
public static void Main()
{
System.Console.Write(new [] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}.SequenceEqual(
new D[] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_019_JaggedArray()
{
// JaggedArray in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new [] {new [] {1}},
new [] {new int[] {2}},
new int[][] {new int[] {3}},
new int[][] {new [] {4}} };
if ( !((a3 is int[][][]) && (a3.Length == 4)) )
{
Console.Write(""Test fail"");
}
else
{
Console.Write(""True"");
}
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_020_MultiDimensionalArray()
{
// MultiDimensionalArray in implicitly typed arrays
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new int[,,] {{{3, 4}}},
new int[,,] {{{3, 4}}} };
if ( !((a3 is int[][,,]) && (a3.Rank == 1) && (a3.Length == 2)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_021_MultiDimensionalArray_02()
{
// Implicitly typed arrays should can be used in creating MultiDimensionalArray
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [,,] { {{2, 3, 4}}, {{2, 3, 4}} };
if ( !((a3 is int[,,]) && (a3.Rank == 3) && (a3.Length == 6)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}
";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_022_GenericMethod()
{
// Implicitly typed arrays used in generic method
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
System.Console.Write(GM(new [] {1, 2, 3}).SequenceEqual(new int[]{1, 2, 3}));
}
public static T GM<T>(T t)
{
return t;
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Query()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int[] ta = new int[] {1, 2, 3, 4, 5};
IEnumerable i = ta;
IEnumerable[] a = new [] {i, from c in ta select c, from c in ta group c by c,
from c in ta select c into g select g, from c in ta where c==3 select c,
from c in ta orderby c select c, from c in ta orderby c ascending select c,
from c in ta orderby c descending select c, from c in ta where c==3 orderby c select c};
Console.Write((a is IEnumerable[]) && (a.Length==9));
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Literal()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write(new [] {true, false}.SequenceEqual(new bool[] {true, false}));
Console.Write(new [] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}.SequenceEqual(
new ulong[] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}));
Console.Write(new [] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}.SequenceEqual(
new long[] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}));
Console.Write(new [] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}.SequenceEqual(
new ulong[] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}));
Console.Write(new [] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}.SequenceEqual(
new long[] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}));
Console.Write(new [] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D}.SequenceEqual(
new double[] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D})) ;
Console.Write(new [] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}.SequenceEqual(
new decimal[] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}.SequenceEqual(
new double[] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}.SequenceEqual(
new decimal[] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}));
}
}
";
CompileAndVerify(
source,
expectedOutput: "TrueTrueTrueTrueTrueTrueTrueTrueTrue");
}
#endregion
#region "Error tests"
[Fact]
public void Error_NonArrayInitExpr()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "3").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[Fact]
public void Error_NonArrayInitExpr_02()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, x, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0103: The name 'x' does not exist in the current context
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[WorkItem(543571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543571")]
[Fact]
public void CS0826ERR_ImplicitlyTypedArrayNoBestType()
{
var text = @"
using System;
namespace Test
{
public class Program
{
enum E
{
Zero,
FortyTwo = 42
};
public static void Main()
{
E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Console.WriteLine(String.Format(""Type={0}, a[0]={1}, a[1]={2}"", a.GetType(), a[0], a[1]));
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (16,21): error CS0826: No best type found for implicitly-typed array
// E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { E.FortyTwo, 0 }").WithLocation(16, 21));
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/Core/Portable/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.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.
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors
{
internal abstract partial class AbstractGenerateDefaultConstructorsService<TService>
{
private class State
{
public INamedTypeSymbol? ClassType { get; private set; }
public ImmutableArray<IMethodSymbol> UnimplementedConstructors { get; private set; }
private State()
{
}
public static State? Generate(
TService service,
SemanticDocument document,
TextSpan textSpan,
bool forRefactoring,
CancellationToken cancellationToken)
{
var state = new State();
if (!state.TryInitialize(service, document, textSpan, forRefactoring, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TService service,
SemanticDocument semanticDocument,
TextSpan textSpan,
bool forRefactoring,
CancellationToken cancellationToken)
{
if (!service.TryInitializeState(semanticDocument, textSpan, cancellationToken, out var classType))
return false;
ClassType = classType;
var baseType = ClassType.BaseType;
if (ClassType.IsStatic ||
baseType == null ||
baseType.TypeKind == TypeKind.Error)
{
return false;
}
// if this is for the refactoring, then don't offer this if the compiler is reporting an
// error here. We'll let the code fix take care of that.
//
// Similarly if this is for the codefix only offer if we do see that there's an error.
var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, fullHeader: true, out _))
{
var fixesError = FixesError(classType, baseType);
if (forRefactoring == fixesError)
return false;
}
var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>();
var classConstructors = ClassType.InstanceConstructors;
var destinationProvider = semanticDocument.Project.Solution.Workspace.Services.GetLanguageServices(ClassType.Language);
var isCaseSensitive = syntaxFacts.IsCaseSensitive;
UnimplementedConstructors =
baseType.InstanceConstructors
.WhereAsArray(c => c.IsAccessibleWithin(ClassType) &&
IsMissing(c, classConstructors, isCaseSensitive));
return UnimplementedConstructors.Length > 0;
}
private static bool FixesError(INamedTypeSymbol classType, INamedTypeSymbol baseType)
{
// See if the user didn't supply a constructor, and thus the compiler automatically generated
// one for them. If so, also see if there's an accessible no-arg contructor in the base.
// If not, then the compiler will error and we want the code-fix to take over solving this problem.
if (classType.Constructors.Any(c => c.Parameters.Length == 0 && c.IsImplicitlyDeclared))
{
var baseNoArgConstructor = baseType.Constructors.FirstOrDefault(c => c.Parameters.Length == 0);
if (baseNoArgConstructor == null ||
!baseNoArgConstructor.IsAccessibleWithin(classType))
{
// this code is in error, but we're the refactoring codepath. Offer nothing
// and let the code fix provider handle it instead.
return true;
}
}
return false;
}
private static bool IsMissing(
IMethodSymbol constructor,
ImmutableArray<IMethodSymbol> classConstructors,
bool isCaseSensitive)
{
var matchingConstructor = classConstructors.FirstOrDefault(
c => SignatureComparer.Instance.HaveSameSignature(
constructor.Parameters, c.Parameters, compareParameterName: true, isCaseSensitive: isCaseSensitive));
if (matchingConstructor == null)
{
return true;
}
// We have a matching constructor in this type. But we'll still offer to create the
// constructor if the constructor that we have is implicit.
return matchingConstructor.IsImplicitlyDeclared;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors
{
internal abstract partial class AbstractGenerateDefaultConstructorsService<TService>
{
private class State
{
public INamedTypeSymbol? ClassType { get; private set; }
public ImmutableArray<IMethodSymbol> UnimplementedConstructors { get; private set; }
private State()
{
}
public static State? Generate(
TService service,
SemanticDocument document,
TextSpan textSpan,
bool forRefactoring,
CancellationToken cancellationToken)
{
var state = new State();
if (!state.TryInitialize(service, document, textSpan, forRefactoring, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TService service,
SemanticDocument semanticDocument,
TextSpan textSpan,
bool forRefactoring,
CancellationToken cancellationToken)
{
if (!service.TryInitializeState(semanticDocument, textSpan, cancellationToken, out var classType))
return false;
ClassType = classType;
var baseType = ClassType.BaseType;
if (ClassType.IsStatic ||
baseType == null ||
baseType.TypeKind == TypeKind.Error)
{
return false;
}
// if this is for the refactoring, then don't offer this if the compiler is reporting an
// error here. We'll let the code fix take care of that.
//
// Similarly if this is for the codefix only offer if we do see that there's an error.
var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, fullHeader: true, out _))
{
var fixesError = FixesError(classType, baseType);
if (forRefactoring == fixesError)
return false;
}
var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>();
var classConstructors = ClassType.InstanceConstructors;
var destinationProvider = semanticDocument.Project.Solution.Workspace.Services.GetLanguageServices(ClassType.Language);
var isCaseSensitive = syntaxFacts.IsCaseSensitive;
UnimplementedConstructors =
baseType.InstanceConstructors
.WhereAsArray(c => c.IsAccessibleWithin(ClassType) &&
IsMissing(c, classConstructors, isCaseSensitive));
return UnimplementedConstructors.Length > 0;
}
private static bool FixesError(INamedTypeSymbol classType, INamedTypeSymbol baseType)
{
// See if the user didn't supply a constructor, and thus the compiler automatically generated
// one for them. If so, also see if there's an accessible no-arg contructor in the base.
// If not, then the compiler will error and we want the code-fix to take over solving this problem.
if (classType.Constructors.Any(c => c.Parameters.Length == 0 && c.IsImplicitlyDeclared))
{
var baseNoArgConstructor = baseType.Constructors.FirstOrDefault(c => c.Parameters.Length == 0);
if (baseNoArgConstructor == null ||
!baseNoArgConstructor.IsAccessibleWithin(classType))
{
// this code is in error, but we're the refactoring codepath. Offer nothing
// and let the code fix provider handle it instead.
return true;
}
}
return false;
}
private static bool IsMissing(
IMethodSymbol constructor,
ImmutableArray<IMethodSymbol> classConstructors,
bool isCaseSensitive)
{
var matchingConstructor = classConstructors.FirstOrDefault(
c => SignatureComparer.Instance.HaveSameSignature(
constructor.Parameters, c.Parameters, compareParameterName: true, isCaseSensitive: isCaseSensitive));
if (matchingConstructor == null)
{
return true;
}
// We have a matching constructor in this type. But we'll still offer to create the
// constructor if the constructor that we have is implicit.
return matchingConstructor.IsImplicitlyDeclared;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptDiagnosticAnalyzerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Shared]
[Export(typeof(IVSTypeScriptDiagnosticAnalyzerService))]
internal sealed class VSTypeScriptAnalyzerService : IVSTypeScriptDiagnosticAnalyzerService
{
private readonly IDiagnosticAnalyzerService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptAnalyzerService(IDiagnosticAnalyzerService service)
=> _service = service;
public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false)
=> _service.Reanalyze(workspace, projectIds, documentIds, highPriority);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Shared]
[Export(typeof(IVSTypeScriptDiagnosticAnalyzerService))]
internal sealed class VSTypeScriptAnalyzerService : IVSTypeScriptDiagnosticAnalyzerService
{
private readonly IDiagnosticAnalyzerService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptAnalyzerService(IDiagnosticAnalyzerService service)
=> _service = service;
public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false)
=> _service.Reanalyze(workspace, projectIds, documentIds, highPriority);
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Semantic/Semantics/BindingAsyncTasklikeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAsyncTasklikeTests : CompilingTestBase
{
[Fact]
public void AsyncTasklikeFromBuilderMethod()
{
var source = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C {
async ValueTask f() { await (Task)null; }
async ValueTask<int> g() { await (Task)null; return 1; }
}
[AsyncMethodBuilder(typeof(string))]
struct ValueTask { }
[AsyncMethodBuilder(typeof(Task<>))]
struct ValueTask<T> { }
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var methodf = compilation.GetMember<MethodSymbol>("C.f");
var methodg = compilation.GetMember<MethodSymbol>("C.g");
Assert.True(methodf.IsAsync);
Assert.True(methodg.IsAsync);
}
[Fact]
public void AsyncTasklikeNotFromDelegate()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static void Main()
{
}
static async Task f()
{
await new Awaitable();
await new Unawaitable(); // error: GetAwaiter must be a field not a delegate
}
static async Tasklike g()
{
await (Task)null;
}
}
class Awaitable
{
public TaskAwaiter GetAwaiter() => (Task.FromResult(1) as Task).GetAwaiter();
}
class Unawaitable
{
public Func<TaskAwaiter> GetAwaiter = () => (Task.FromResult(1) as Task).GetAwaiter();
}
[AsyncMethodBuilder(typeof(TasklikeMethodBuilder))]
public class Tasklike { }
public class TasklikeMethodBuilder
{
public static TasklikeMethodBuilder Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult() { }
public void SetException(Exception exception) { }
private void EnsureTaskBuilder() { }
public Tasklike Task => null;
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 { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (15,9): error CS0118: 'GetAwaiter' is a field but is used like a method
// await new Unawaitable(); // error: GetAwaiter must be a field not a delegate
Diagnostic(ErrorCode.ERR_BadSKknown, "await new Unawaitable()").WithArguments("GetAwaiter", "field", "method").WithLocation(15, 9)
);
}
private bool VerifyTaskOverloads(string arg, string betterOverload, string worseOverload, bool implicitConversionToTask = false, bool isError = false)
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
#pragma warning disable CS1998
static void Main()
{
var s = (<<arg>>);
Console.Write(s);
}
<<betterOverload>>
<<worseOverload>>
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))]
struct ValueTask
{
<<implicitConversionToTask>>
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))]
struct ValueTask<T>
{
internal T _result;
<<implicitConversionToTaskT>>
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private ValueTask<T> _task;
internal Awaiter(ValueTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
sealed class ValueTaskMethodBuilder
{
private ValueTask _task = new ValueTask();
public static ValueTaskMethodBuilder Create() => new ValueTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
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 ValueTask Task => _task;
}
sealed class ValueTaskMethodBuilder<T>
{
private ValueTask<T> _task = new ValueTask<T>();
public static ValueTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
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 ValueTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
source = source.Replace("<<arg>>", arg);
source = source.Replace("<<betterOverload>>", (betterOverload != null) ? "static string " + betterOverload + " => \"better\";" : "");
source = source.Replace("<<worseOverload>>", (worseOverload != null) ? "static string " + worseOverload + " => \"worse\";" : "");
source = source.Replace("<<implicitConversionToTask>>", implicitConversionToTask ? "public static implicit operator Task(ValueTask t) => Task.FromResult(0);" : "");
source = source.Replace("<<implicitConversionToTaskT>>", implicitConversionToTask ? "public static implicit operator Task<T>(ValueTask<T> t) => Task.FromResult<T>(t._result);" : "");
if (isError)
{
var compilation = CreateCompilationWithMscorlib45(source);
var diagnostics = compilation.GetDiagnostics();
Assert.True(diagnostics.Length == 1);
Assert.True(diagnostics.First().Code == (int)ErrorCode.ERR_AmbigCall);
}
else
{
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "better");
}
return true;
}
[Fact]
public bool TasklikeA3() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
null);
[Fact]
public void TasklikeA3n() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
null);
[Fact]
public void TasklikeA4() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> labda)",
null);
[Fact]
public void TasklikeA5s() => VerifyTaskOverloads("f(() => 3)",
"f<T>(Func<T> lambda)",
"f<T>(Func<ValueTask<T>> lambda)");
[Fact]
public void TasklikeA5a() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<T> lambda)");
[Fact]
public void TasklikeA6() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<ValueTask<double>> lambda)");
[Fact]
public void TasklikeA7() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<byte>> lambda)",
"f(Func<ValueTask<short>> lambda)");
[Fact]
public void TasklikeA8() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Action lambda)");
[Fact]
public void TasklikeB7_ic0() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<int>> lambda)",
isError: true);
[Fact]
public void TasklikeB7_ic1() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<int>> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeB7g_ic0() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<Task<T>> lambda)",
isError: true);
[Fact]
public void TasklikeB7g_ic1() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<Task<T>> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeB7n_ic0() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Func<Task> lambda)",
isError: true);
[Fact]
public void TasklikeB7n_ic1() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Func<Task> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeC1() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<double>> lambda)");
[Fact]
public void TasklikeC2() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<byte>> lambda)",
"f(Func<Task<short>> lambda)");
[Fact]
public void TasklikeC5() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f<T>(Func<Task<T>> lambda)");
[Fact]
public void AsyncTasklikeMethod()
{
var source = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C {
async ValueTask f() { await Task.Delay(0); }
async ValueTask<int> g() { await Task.Delay(0); return 1; }
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))]
struct ValueTask { }
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))]
struct ValueTask<T> { }
class ValueTaskMethodBuilder {}
class ValueTaskMethodBuilder<T> {}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var methodf = compilation.GetMember<MethodSymbol>("C.f");
var methodg = compilation.GetMember<MethodSymbol>("C.g");
Assert.True(methodf.IsAsync);
Assert.True(methodg.IsAsync);
}
[Fact]
public void NotTasklike()
{
var source1 = @"
using System.Threading.Tasks;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
public class MyTask { }
";
CreateCompilationWithMscorlib45(source1).VerifyDiagnostics(
// (6,18): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(6, 18),
// (6,18): error CS0161: 'C.f()': not all code paths return a value
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_ReturnExpected, "f").WithArguments("C.f()").WithLocation(6, 18)
);
var source2 = @"
using System.Threading.Tasks;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
public class MyTask { }
";
CreateCompilationWithMscorlib45(source2).VerifyDiagnostics(
// (6,18): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(6, 18),
// (6,18): error CS0161: 'C.f()': not all code paths return a value
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_ReturnExpected, "f").WithArguments("C.f()").WithLocation(6, 18)
);
var source3 = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder))]
public class MyTask { }
public class MyTaskBuilder
{
public static MyTaskBuilder Create() => null;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source3).VerifyDiagnostics();
}
[Fact]
public void AsyncTasklikeOverloadLambdas()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C {
static void Main() {
f(async () => { await (Task)null; return 1; });
h(async () => { await (Task)null; });
}
static void f<T>(Func<MyTask<T>> lambda) { }
static void f<T>(Func<T> lambda) { }
static void f<T>(T arg) { }
static void h(Func<MyTask> lambda) { }
static void h(Func<Task> lambda) { }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder<>))]
public class MyTask<T> { }
public class MyTaskBuilder<T> {
public static MyTaskBuilder<T> Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult(T result) { }
public void SetException(Exception exception) { }
public MyTask<T> Task => default(MyTask<T>);
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 { }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder))]
public class MyTask { }
public class MyTaskBuilder
{
public static MyTaskBuilder Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult() { }
public void SetException(Exception exception) { }
public MyTask Task => default(MyTask);
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 { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.h(Func<MyTask>)' and 'C.h(Func<Task>)'
// h(async () => { await (Task)null; });
Diagnostic(ErrorCode.ERR_AmbigCall, "h").WithArguments("C.h(System.Func<MyTask>)", "C.h(System.Func<System.Threading.Tasks.Task>)").WithLocation(8, 9)
);
}
[Fact]
public void AsyncTasklikeInadmissibleArity()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C {
async Mismatch2<int,int> g() { await Task.Delay(0); return 1; }
}
[AsyncMethodBuilder(typeof(Mismatch2MethodBuilder<>))]
struct Mismatch2<T,U> { }
class Mismatch2MethodBuilder<T> {}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyEmitDiagnostics(
// (5,30): error CS1983: The return type of an async method must be void, Task or Task<T>
// async Mismatch2<int,int> g() { await Task.Delay(0); return 1; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "g").WithLocation(5, 30)
);
}
[Fact]
public void AsyncTasklikeOverloadInvestigations()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static Task<int> arg1 = null;
static int arg2 = 0;
static int f1(MyTask<int> t) => 0;
static int f1(Task<int> t) => 1;
static int r1 = f1(arg1); // 1
static void Main()
{
Console.Write(r1);
}
}
[AsyncMethodBuilder(typeof(ValueTaskBuilder<>))]
class ValueTask<T>
{
public static implicit operator ValueTask<T>(Task<T> task) => null;
}
[AsyncMethodBuilder(typeof(MyTaskBuilder<>))]
class MyTask<T>
{
public static implicit operator MyTask<T>(Task<T> task) => null;
public static implicit operator Task<T>(MyTask<T> mytask) => null;
}
class ValueTaskBuilder<T>
{
public static ValueTaskBuilder<T> Create() => null;
public void Start<TSM>(ref TSM sm) where TSM : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine sm) { }
public void SetResult(T r) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
public void AwaitOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
}
class MyTaskBuilder<T>
{
public static MyTaskBuilder<T> Create() => null;
public void Start<TSM>(ref TSM sm) where TSM : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine sm) { }
public void SetResult(T r) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
public void AwaitOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "1");
}
[Fact]
public void AsyncTasklikeBetterness()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static char f1(Func<ValueTask<short>> lambda) => 's';
static char f1(Func<Task<byte>> lambda) => 'b';
static char f2(Func<Task<short>> lambda) => 's';
static char f2(Func<ValueTask<byte>> lambda) => 'b';
static char f3(Func<Task<short>> lambda) => 's';
static char f3(Func<Task<byte>> lambda) => 'b';
static char f4(Func<ValueTask<short>> lambda) => 's';
static char f4(Func<ValueTask<byte>> lambda) => 'b';
static void Main()
{
Console.Write(f1(async () => { await (Task)null; return 9; }));
Console.Write(f2(async () => { await (Task)null; return 9; }));
Console.Write(f3(async () => { await (Task)null; return 9; }));
Console.Write(f4(async () => { await (Task)null; return 9; }));
}
}
[AsyncMethodBuilder(typeof(ValueTaskBuilder<>))]
public class ValueTask<T> { }
public class ValueTaskBuilder<T>
{
public static ValueTaskBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TSM>(ref TSM stateMachine) where TSM : IAsyncStateMachine { }
public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
public void SetResult(T result) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "bbbb");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAsyncTasklikeTests : CompilingTestBase
{
[Fact]
public void AsyncTasklikeFromBuilderMethod()
{
var source = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C {
async ValueTask f() { await (Task)null; }
async ValueTask<int> g() { await (Task)null; return 1; }
}
[AsyncMethodBuilder(typeof(string))]
struct ValueTask { }
[AsyncMethodBuilder(typeof(Task<>))]
struct ValueTask<T> { }
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var methodf = compilation.GetMember<MethodSymbol>("C.f");
var methodg = compilation.GetMember<MethodSymbol>("C.g");
Assert.True(methodf.IsAsync);
Assert.True(methodg.IsAsync);
}
[Fact]
public void AsyncTasklikeNotFromDelegate()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static void Main()
{
}
static async Task f()
{
await new Awaitable();
await new Unawaitable(); // error: GetAwaiter must be a field not a delegate
}
static async Tasklike g()
{
await (Task)null;
}
}
class Awaitable
{
public TaskAwaiter GetAwaiter() => (Task.FromResult(1) as Task).GetAwaiter();
}
class Unawaitable
{
public Func<TaskAwaiter> GetAwaiter = () => (Task.FromResult(1) as Task).GetAwaiter();
}
[AsyncMethodBuilder(typeof(TasklikeMethodBuilder))]
public class Tasklike { }
public class TasklikeMethodBuilder
{
public static TasklikeMethodBuilder Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult() { }
public void SetException(Exception exception) { }
private void EnsureTaskBuilder() { }
public Tasklike Task => null;
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 { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (15,9): error CS0118: 'GetAwaiter' is a field but is used like a method
// await new Unawaitable(); // error: GetAwaiter must be a field not a delegate
Diagnostic(ErrorCode.ERR_BadSKknown, "await new Unawaitable()").WithArguments("GetAwaiter", "field", "method").WithLocation(15, 9)
);
}
private bool VerifyTaskOverloads(string arg, string betterOverload, string worseOverload, bool implicitConversionToTask = false, bool isError = false)
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
#pragma warning disable CS1998
static void Main()
{
var s = (<<arg>>);
Console.Write(s);
}
<<betterOverload>>
<<worseOverload>>
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))]
struct ValueTask
{
<<implicitConversionToTask>>
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))]
struct ValueTask<T>
{
internal T _result;
<<implicitConversionToTaskT>>
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private ValueTask<T> _task;
internal Awaiter(ValueTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
sealed class ValueTaskMethodBuilder
{
private ValueTask _task = new ValueTask();
public static ValueTaskMethodBuilder Create() => new ValueTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
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 ValueTask Task => _task;
}
sealed class ValueTaskMethodBuilder<T>
{
private ValueTask<T> _task = new ValueTask<T>();
public static ValueTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
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 ValueTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
source = source.Replace("<<arg>>", arg);
source = source.Replace("<<betterOverload>>", (betterOverload != null) ? "static string " + betterOverload + " => \"better\";" : "");
source = source.Replace("<<worseOverload>>", (worseOverload != null) ? "static string " + worseOverload + " => \"worse\";" : "");
source = source.Replace("<<implicitConversionToTask>>", implicitConversionToTask ? "public static implicit operator Task(ValueTask t) => Task.FromResult(0);" : "");
source = source.Replace("<<implicitConversionToTaskT>>", implicitConversionToTask ? "public static implicit operator Task<T>(ValueTask<T> t) => Task.FromResult<T>(t._result);" : "");
if (isError)
{
var compilation = CreateCompilationWithMscorlib45(source);
var diagnostics = compilation.GetDiagnostics();
Assert.True(diagnostics.Length == 1);
Assert.True(diagnostics.First().Code == (int)ErrorCode.ERR_AmbigCall);
}
else
{
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "better");
}
return true;
}
[Fact]
public bool TasklikeA3() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
null);
[Fact]
public void TasklikeA3n() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
null);
[Fact]
public void TasklikeA4() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> labda)",
null);
[Fact]
public void TasklikeA5s() => VerifyTaskOverloads("f(() => 3)",
"f<T>(Func<T> lambda)",
"f<T>(Func<ValueTask<T>> lambda)");
[Fact]
public void TasklikeA5a() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<T> lambda)");
[Fact]
public void TasklikeA6() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<ValueTask<double>> lambda)");
[Fact]
public void TasklikeA7() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<byte>> lambda)",
"f(Func<ValueTask<short>> lambda)");
[Fact]
public void TasklikeA8() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Action lambda)");
[Fact]
public void TasklikeB7_ic0() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<int>> lambda)",
isError: true);
[Fact]
public void TasklikeB7_ic1() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<int>> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeB7g_ic0() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<Task<T>> lambda)",
isError: true);
[Fact]
public void TasklikeB7g_ic1() => VerifyTaskOverloads("f(async () => 3)",
"f<T>(Func<ValueTask<T>> lambda)",
"f<T>(Func<Task<T>> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeB7n_ic0() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Func<Task> lambda)",
isError: true);
[Fact]
public void TasklikeB7n_ic1() => VerifyTaskOverloads("f(async () => {})",
"f(Func<ValueTask> lambda)",
"f(Func<Task> lambda)",
implicitConversionToTask: true);
[Fact]
public void TasklikeC1() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f(Func<Task<double>> lambda)");
[Fact]
public void TasklikeC2() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<byte>> lambda)",
"f(Func<Task<short>> lambda)");
[Fact]
public void TasklikeC5() => VerifyTaskOverloads("f(async () => 3)",
"f(Func<ValueTask<int>> lambda)",
"f<T>(Func<Task<T>> lambda)");
[Fact]
public void AsyncTasklikeMethod()
{
var source = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C {
async ValueTask f() { await Task.Delay(0); }
async ValueTask<int> g() { await Task.Delay(0); return 1; }
}
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))]
struct ValueTask { }
[AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))]
struct ValueTask<T> { }
class ValueTaskMethodBuilder {}
class ValueTaskMethodBuilder<T> {}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var methodf = compilation.GetMember<MethodSymbol>("C.f");
var methodg = compilation.GetMember<MethodSymbol>("C.g");
Assert.True(methodf.IsAsync);
Assert.True(methodg.IsAsync);
}
[Fact]
public void NotTasklike()
{
var source1 = @"
using System.Threading.Tasks;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
public class MyTask { }
";
CreateCompilationWithMscorlib45(source1).VerifyDiagnostics(
// (6,18): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(6, 18),
// (6,18): error CS0161: 'C.f()': not all code paths return a value
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_ReturnExpected, "f").WithArguments("C.f()").WithLocation(6, 18)
);
var source2 = @"
using System.Threading.Tasks;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
public class MyTask { }
";
CreateCompilationWithMscorlib45(source2).VerifyDiagnostics(
// (6,18): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(6, 18),
// (6,18): error CS0161: 'C.f()': not all code paths return a value
// async MyTask f() { await (Task)null; }
Diagnostic(ErrorCode.ERR_ReturnExpected, "f").WithArguments("C.f()").WithLocation(6, 18)
);
var source3 = @"
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class C
{
static void Main() { }
async MyTask f() { await (Task)null; }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder))]
public class MyTask { }
public class MyTaskBuilder
{
public static MyTaskBuilder Create() => null;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source3).VerifyDiagnostics();
}
[Fact]
public void AsyncTasklikeOverloadLambdas()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C {
static void Main() {
f(async () => { await (Task)null; return 1; });
h(async () => { await (Task)null; });
}
static void f<T>(Func<MyTask<T>> lambda) { }
static void f<T>(Func<T> lambda) { }
static void f<T>(T arg) { }
static void h(Func<MyTask> lambda) { }
static void h(Func<Task> lambda) { }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder<>))]
public class MyTask<T> { }
public class MyTaskBuilder<T> {
public static MyTaskBuilder<T> Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult(T result) { }
public void SetException(Exception exception) { }
public MyTask<T> Task => default(MyTask<T>);
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 { }
}
[AsyncMethodBuilder(typeof(MyTaskBuilder))]
public class MyTask { }
public class MyTaskBuilder
{
public static MyTaskBuilder Create() => null;
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void SetResult() { }
public void SetException(Exception exception) { }
public MyTask Task => default(MyTask);
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 { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.h(Func<MyTask>)' and 'C.h(Func<Task>)'
// h(async () => { await (Task)null; });
Diagnostic(ErrorCode.ERR_AmbigCall, "h").WithArguments("C.h(System.Func<MyTask>)", "C.h(System.Func<System.Threading.Tasks.Task>)").WithLocation(8, 9)
);
}
[Fact]
public void AsyncTasklikeInadmissibleArity()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C {
async Mismatch2<int,int> g() { await Task.Delay(0); return 1; }
}
[AsyncMethodBuilder(typeof(Mismatch2MethodBuilder<>))]
struct Mismatch2<T,U> { }
class Mismatch2MethodBuilder<T> {}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyEmitDiagnostics(
// (5,30): error CS1983: The return type of an async method must be void, Task or Task<T>
// async Mismatch2<int,int> g() { await Task.Delay(0); return 1; }
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "g").WithLocation(5, 30)
);
}
[Fact]
public void AsyncTasklikeOverloadInvestigations()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static Task<int> arg1 = null;
static int arg2 = 0;
static int f1(MyTask<int> t) => 0;
static int f1(Task<int> t) => 1;
static int r1 = f1(arg1); // 1
static void Main()
{
Console.Write(r1);
}
}
[AsyncMethodBuilder(typeof(ValueTaskBuilder<>))]
class ValueTask<T>
{
public static implicit operator ValueTask<T>(Task<T> task) => null;
}
[AsyncMethodBuilder(typeof(MyTaskBuilder<>))]
class MyTask<T>
{
public static implicit operator MyTask<T>(Task<T> task) => null;
public static implicit operator Task<T>(MyTask<T> mytask) => null;
}
class ValueTaskBuilder<T>
{
public static ValueTaskBuilder<T> Create() => null;
public void Start<TSM>(ref TSM sm) where TSM : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine sm) { }
public void SetResult(T r) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
public void AwaitOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
}
class MyTaskBuilder<T>
{
public static MyTaskBuilder<T> Create() => null;
public void Start<TSM>(ref TSM sm) where TSM : IAsyncStateMachine { }
public void SetStateMachine(IAsyncStateMachine sm) { }
public void SetResult(T r) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
public void AwaitOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA a, ref TSM sm) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "1");
}
[Fact]
public void AsyncTasklikeBetterness()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class Program
{
static char f1(Func<ValueTask<short>> lambda) => 's';
static char f1(Func<Task<byte>> lambda) => 'b';
static char f2(Func<Task<short>> lambda) => 's';
static char f2(Func<ValueTask<byte>> lambda) => 'b';
static char f3(Func<Task<short>> lambda) => 's';
static char f3(Func<Task<byte>> lambda) => 'b';
static char f4(Func<ValueTask<short>> lambda) => 's';
static char f4(Func<ValueTask<byte>> lambda) => 'b';
static void Main()
{
Console.Write(f1(async () => { await (Task)null; return 9; }));
Console.Write(f2(async () => { await (Task)null; return 9; }));
Console.Write(f3(async () => { await (Task)null; return 9; }));
Console.Write(f4(async () => { await (Task)null; return 9; }));
}
}
[AsyncMethodBuilder(typeof(ValueTaskBuilder<>))]
public class ValueTask<T> { }
public class ValueTaskBuilder<T>
{
public static ValueTaskBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TSM>(ref TSM stateMachine) where TSM : IAsyncStateMachine { }
public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : INotifyCompletion where TSM : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : ICriticalNotifyCompletion where TSM : IAsyncStateMachine { }
public void SetResult(T result) { }
public void SetException(Exception ex) { }
public ValueTask<T> Task => null;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: "bbbb");
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingServiceDescriptorsWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime;
using MessagePack;
using MessagePack.Formatters;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal readonly struct UnitTestingServiceDescriptorsWrapper
{
internal readonly ServiceDescriptors UnderlyingObject;
public UnitTestingServiceDescriptorsWrapper(
string componentName,
Func<string, string> featureDisplayNameProvider,
ImmutableArray<IMessagePackFormatter> additionalFormatters,
ImmutableArray<IFormatterResolver> additionalResolvers,
IEnumerable<(Type serviceInterface, Type? callbackInterface)> interfaces)
=> UnderlyingObject = new ServiceDescriptors(componentName, featureDisplayNameProvider, new RemoteSerializationOptions(additionalFormatters, additionalResolvers), interfaces);
/// <summary>
/// To be called from a service factory in OOP.
/// </summary>
public ServiceJsonRpcDescriptor GetDescriptorForServiceFactory(Type serviceInterface)
=> UnderlyingObject.GetServiceDescriptorForServiceFactory(serviceInterface);
public MessagePackSerializerOptions MessagePackOptions
=> UnderlyingObject.Options.MessagePackOptions;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime;
using MessagePack;
using MessagePack.Formatters;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal readonly struct UnitTestingServiceDescriptorsWrapper
{
internal readonly ServiceDescriptors UnderlyingObject;
public UnitTestingServiceDescriptorsWrapper(
string componentName,
Func<string, string> featureDisplayNameProvider,
ImmutableArray<IMessagePackFormatter> additionalFormatters,
ImmutableArray<IFormatterResolver> additionalResolvers,
IEnumerable<(Type serviceInterface, Type? callbackInterface)> interfaces)
=> UnderlyingObject = new ServiceDescriptors(componentName, featureDisplayNameProvider, new RemoteSerializationOptions(additionalFormatters, additionalResolvers), interfaces);
/// <summary>
/// To be called from a service factory in OOP.
/// </summary>
public ServiceJsonRpcDescriptor GetDescriptorForServiceFactory(Type serviceInterface)
=> UnderlyingObject.GetServiceDescriptorForServiceFactory(serviceInterface);
public MessagePackSerializerOptions MessagePackOptions
=> UnderlyingObject.Options.MessagePackOptions;
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Core/ExportContentTypeLanguageServiceAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor
{
/// <summary>
/// Specifies the exact type of the service exported by the ILanguageService.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportContentTypeLanguageServiceAttribute : ExportLanguageServiceAttribute
{
public string DefaultContentType { get; set; }
public ExportContentTypeLanguageServiceAttribute(string defaultContentType, string language, string layer = ServiceLayer.Default)
: base(typeof(IContentTypeLanguageService), language, layer)
{
this.DefaultContentType = defaultContentType ?? throw new ArgumentNullException(nameof(defaultContentType));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor
{
/// <summary>
/// Specifies the exact type of the service exported by the ILanguageService.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportContentTypeLanguageServiceAttribute : ExportLanguageServiceAttribute
{
public string DefaultContentType { get; set; }
public ExportContentTypeLanguageServiceAttribute(string defaultContentType, string language, string layer = ServiceLayer.Default)
: base(typeof(IContentTypeLanguageService), language, layer)
{
this.DefaultContentType = defaultContentType ?? throw new ArgumentNullException(nameof(defaultContentType));
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitConversionSymbols.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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
#Region "C#"
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionPredefinedType_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$Int32|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]Int32)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$System.Int32|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]System.Int32)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionArrayType_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int[]|}(Goo value) => default;
static void M()
{
_ = [|(|]int[])new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
#End Region
#Region "Visual Basic"
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionPredefinedType_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType1_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as int32
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType2_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer)
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), int32)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType1_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as system.int32
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType2_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), system.int32)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionArrayType_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer()
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer())
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
#End Region
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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
#Region "C#"
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionPredefinedType_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$Int32|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]Int32)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$System.Int32|}(Goo value) => default;
static void M()
{
_ = [|(|]int)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int|}(Goo value) => default;
static void M()
{
_ = [|(|]System.Int32)new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionArrayType_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct Goo
{
public static explicit operator {|Definition:$$int[]|}(Goo value) => default;
static void M()
{
_ = [|(|]int[])new Goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
#End Region
#Region "Visual Basic"
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionPredefinedType_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType1_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as int32
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionNamedType2_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer)
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), int32)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType1_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as system.int32
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionQualifiedNamedType2_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), system.int32)
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(50850, "https://github.com/dotnet/roslyn/issues/50850")>
Public Async Function TestExplicitConversionArrayType_VisualBasic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports system
structure Goo
Public Shared Narrowing Operator {|Definition:$$CType|}(value as goo) as integer()
return nothing
end operator
sub M()
dim y = [|ctype|](new Goo(), integer())
end sub
end structure
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
#End Region
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.WorkItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
internal partial class WorkCoordinator
{
// this is internal only type
private readonly struct WorkItem
{
// project related workitem
public readonly ProjectId ProjectId;
// document related workitem
public readonly DocumentId? DocumentId;
public readonly string Language;
public readonly InvocationReasons InvocationReasons;
public readonly bool IsLowPriority;
// extra info
public readonly SyntaxPath? ActiveMember;
/// <summary>
/// Non-empty if this work item is intended to be executed only for specific incremental analyzer(s).
/// Otherwise, the work item is applicable to all relevant incremental analyzers.
/// </summary>
public readonly ImmutableHashSet<IIncrementalAnalyzer> SpecificAnalyzers;
/// <summary>
/// Gets all the applicable analyzers to execute for this work item.
/// If this work item has any specific analyzer(s), then returns the intersection of <see cref="SpecificAnalyzers"/>
/// and the given <paramref name="allAnalyzers"/>.
/// Otherwise, returns <paramref name="allAnalyzers"/>.
/// </summary>
public IEnumerable<IIncrementalAnalyzer> GetApplicableAnalyzers(ImmutableArray<IIncrementalAnalyzer> allAnalyzers)
=> SpecificAnalyzers?.Count > 0 ? SpecificAnalyzers.Where(allAnalyzers.Contains) : allAnalyzers;
// retry
public readonly bool IsRetry;
// common
public readonly IAsyncToken AsyncToken;
public bool MustRefresh
{
get
{
// in current design, we need to re-run all incremental analyzer on document open and close
// so that incremental analyzer who only cares about opened document can have a chance to clean up
// its state.
return InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened) ||
InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed);
}
}
private WorkItem(
DocumentId? documentId,
ProjectId projectId,
string language,
InvocationReasons invocationReasons,
bool isLowPriority,
SyntaxPath? activeMember,
ImmutableHashSet<IIncrementalAnalyzer> specificAnalyzers,
bool retry,
IAsyncToken asyncToken)
{
Debug.Assert(documentId == null || documentId.ProjectId == projectId);
DocumentId = documentId;
ProjectId = projectId;
Language = language;
InvocationReasons = invocationReasons;
IsLowPriority = isLowPriority;
ActiveMember = activeMember;
SpecificAnalyzers = specificAnalyzers;
IsRetry = retry;
AsyncToken = asyncToken;
}
public WorkItem(DocumentId documentId, string language, InvocationReasons invocationReasons, bool isLowPriority, SyntaxPath? activeMember, IAsyncToken asyncToken)
: this(documentId, documentId.ProjectId, language, invocationReasons, isLowPriority, activeMember, ImmutableHashSet.Create<IIncrementalAnalyzer>(), retry: false, asyncToken)
{
}
public WorkItem(DocumentId documentId, string language, InvocationReasons invocationReasons, bool isLowPriority, IIncrementalAnalyzer? analyzer, IAsyncToken asyncToken)
: this(documentId, documentId.ProjectId, language, invocationReasons, isLowPriority, activeMember: null,
analyzer == null ? ImmutableHashSet.Create<IIncrementalAnalyzer>() : ImmutableHashSet.Create(analyzer),
retry: false, asyncToken)
{
}
public object Key => DocumentId ?? (object)ProjectId;
private ImmutableHashSet<IIncrementalAnalyzer> Union(ImmutableHashSet<IIncrementalAnalyzer> analyzers)
{
if (analyzers.IsEmpty)
{
return SpecificAnalyzers;
}
if (SpecificAnalyzers.IsEmpty)
{
return analyzers;
}
return SpecificAnalyzers.Union(analyzers);
}
public WorkItem Retry(IAsyncToken asyncToken)
{
return new WorkItem(
DocumentId, ProjectId, Language, InvocationReasons, IsLowPriority, ActiveMember, SpecificAnalyzers,
retry: true, asyncToken: asyncToken);
}
public WorkItem With(
InvocationReasons invocationReasons, SyntaxPath? currentMember,
ImmutableHashSet<IIncrementalAnalyzer> analyzers, bool retry, IAsyncToken asyncToken)
{
// dispose old one
AsyncToken.Dispose();
// create new work item
return new WorkItem(
DocumentId, ProjectId, Language,
InvocationReasons.With(invocationReasons),
IsLowPriority,
ActiveMember == currentMember ? currentMember : null,
Union(analyzers), IsRetry || retry,
asyncToken);
}
public WorkItem WithAsyncToken(IAsyncToken asyncToken)
{
return new WorkItem(
DocumentId, ProjectId, Language, InvocationReasons, IsLowPriority, ActiveMember, SpecificAnalyzers,
retry: false, asyncToken: asyncToken);
}
public WorkItem ToProjectWorkItem(IAsyncToken asyncToken)
{
RoslynDebug.Assert(DocumentId != null);
// create new work item that represents work per project
return new WorkItem(
documentId: null,
DocumentId.ProjectId,
Language,
InvocationReasons,
IsLowPriority,
ActiveMember,
SpecificAnalyzers,
IsRetry,
asyncToken);
}
public WorkItem With(ImmutableHashSet<IIncrementalAnalyzer> specificAnalyzers, IAsyncToken asyncToken)
{
return new WorkItem(DocumentId, ProjectId, Language, InvocationReasons,
IsLowPriority, ActiveMember, specificAnalyzers, IsRetry, asyncToken);
}
public override string ToString()
=> $"{DocumentId?.ToString() ?? ProjectId.ToString()}, ({InvocationReasons}), LowPriority:{IsLowPriority}, ActiveMember:{ActiveMember != null}, Retry:{IsRetry}, ({string.Join("|", SpecificAnalyzers.Select(a => a.GetType().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.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
internal partial class WorkCoordinator
{
// this is internal only type
private readonly struct WorkItem
{
// project related workitem
public readonly ProjectId ProjectId;
// document related workitem
public readonly DocumentId? DocumentId;
public readonly string Language;
public readonly InvocationReasons InvocationReasons;
public readonly bool IsLowPriority;
// extra info
public readonly SyntaxPath? ActiveMember;
/// <summary>
/// Non-empty if this work item is intended to be executed only for specific incremental analyzer(s).
/// Otherwise, the work item is applicable to all relevant incremental analyzers.
/// </summary>
public readonly ImmutableHashSet<IIncrementalAnalyzer> SpecificAnalyzers;
/// <summary>
/// Gets all the applicable analyzers to execute for this work item.
/// If this work item has any specific analyzer(s), then returns the intersection of <see cref="SpecificAnalyzers"/>
/// and the given <paramref name="allAnalyzers"/>.
/// Otherwise, returns <paramref name="allAnalyzers"/>.
/// </summary>
public IEnumerable<IIncrementalAnalyzer> GetApplicableAnalyzers(ImmutableArray<IIncrementalAnalyzer> allAnalyzers)
=> SpecificAnalyzers?.Count > 0 ? SpecificAnalyzers.Where(allAnalyzers.Contains) : allAnalyzers;
// retry
public readonly bool IsRetry;
// common
public readonly IAsyncToken AsyncToken;
public bool MustRefresh
{
get
{
// in current design, we need to re-run all incremental analyzer on document open and close
// so that incremental analyzer who only cares about opened document can have a chance to clean up
// its state.
return InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened) ||
InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed);
}
}
private WorkItem(
DocumentId? documentId,
ProjectId projectId,
string language,
InvocationReasons invocationReasons,
bool isLowPriority,
SyntaxPath? activeMember,
ImmutableHashSet<IIncrementalAnalyzer> specificAnalyzers,
bool retry,
IAsyncToken asyncToken)
{
Debug.Assert(documentId == null || documentId.ProjectId == projectId);
DocumentId = documentId;
ProjectId = projectId;
Language = language;
InvocationReasons = invocationReasons;
IsLowPriority = isLowPriority;
ActiveMember = activeMember;
SpecificAnalyzers = specificAnalyzers;
IsRetry = retry;
AsyncToken = asyncToken;
}
public WorkItem(DocumentId documentId, string language, InvocationReasons invocationReasons, bool isLowPriority, SyntaxPath? activeMember, IAsyncToken asyncToken)
: this(documentId, documentId.ProjectId, language, invocationReasons, isLowPriority, activeMember, ImmutableHashSet.Create<IIncrementalAnalyzer>(), retry: false, asyncToken)
{
}
public WorkItem(DocumentId documentId, string language, InvocationReasons invocationReasons, bool isLowPriority, IIncrementalAnalyzer? analyzer, IAsyncToken asyncToken)
: this(documentId, documentId.ProjectId, language, invocationReasons, isLowPriority, activeMember: null,
analyzer == null ? ImmutableHashSet.Create<IIncrementalAnalyzer>() : ImmutableHashSet.Create(analyzer),
retry: false, asyncToken)
{
}
public object Key => DocumentId ?? (object)ProjectId;
private ImmutableHashSet<IIncrementalAnalyzer> Union(ImmutableHashSet<IIncrementalAnalyzer> analyzers)
{
if (analyzers.IsEmpty)
{
return SpecificAnalyzers;
}
if (SpecificAnalyzers.IsEmpty)
{
return analyzers;
}
return SpecificAnalyzers.Union(analyzers);
}
public WorkItem Retry(IAsyncToken asyncToken)
{
return new WorkItem(
DocumentId, ProjectId, Language, InvocationReasons, IsLowPriority, ActiveMember, SpecificAnalyzers,
retry: true, asyncToken: asyncToken);
}
public WorkItem With(
InvocationReasons invocationReasons, SyntaxPath? currentMember,
ImmutableHashSet<IIncrementalAnalyzer> analyzers, bool retry, IAsyncToken asyncToken)
{
// dispose old one
AsyncToken.Dispose();
// create new work item
return new WorkItem(
DocumentId, ProjectId, Language,
InvocationReasons.With(invocationReasons),
IsLowPriority,
ActiveMember == currentMember ? currentMember : null,
Union(analyzers), IsRetry || retry,
asyncToken);
}
public WorkItem WithAsyncToken(IAsyncToken asyncToken)
{
return new WorkItem(
DocumentId, ProjectId, Language, InvocationReasons, IsLowPriority, ActiveMember, SpecificAnalyzers,
retry: false, asyncToken: asyncToken);
}
public WorkItem ToProjectWorkItem(IAsyncToken asyncToken)
{
RoslynDebug.Assert(DocumentId != null);
// create new work item that represents work per project
return new WorkItem(
documentId: null,
DocumentId.ProjectId,
Language,
InvocationReasons,
IsLowPriority,
ActiveMember,
SpecificAnalyzers,
IsRetry,
asyncToken);
}
public WorkItem With(ImmutableHashSet<IIncrementalAnalyzer> specificAnalyzers, IAsyncToken asyncToken)
{
return new WorkItem(DocumentId, ProjectId, Language, InvocationReasons,
IsLowPriority, ActiveMember, specificAnalyzers, IsRetry, asyncToken);
}
public override string ToString()
=> $"{DocumentId?.ToString() ?? ProjectId.ToString()}, ({InvocationReasons}), LowPriority:{IsLowPriority}, ActiveMember:{ActiveMember != null}, Retry:{IsRetry}, ({string.Join("|", SpecificAnalyzers.Select(a => a.GetType().Name))})";
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ExternKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass()
{
await VerifyKeywordAsync(
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"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 = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStaticInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (c)
{
case 0:
[Foo]
$$
}", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndCallStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterExternInStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternKeyword()
=> await VerifyAbsenceAsync(@"extern $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousExternAlias()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternKeyword_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
extern $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousExternAlias_InsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsing_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespace_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
{
await VerifyAbsenceAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExtern()
{
await VerifyAbsenceAsync(
@"class C {
extern $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ExternKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass()
{
await VerifyKeywordAsync(
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"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 = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStaticInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (c)
{
case 0:
[Foo]
$$
}", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBetweenAttributesAndCallStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterExternInStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternKeyword()
=> await VerifyAbsenceAsync(@"extern $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousExternAlias()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternKeyword_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
extern $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousExternAlias_InsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsing_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespace_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
{
await VerifyAbsenceAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExtern()
{
await VerifyAbsenceAsync(
@"class C {
extern $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Test/Core/Assert/DiffUtil.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class DiffUtil
{
private enum EditKind
{
/// <summary>
/// No change.
/// </summary>
None = 0,
/// <summary>
/// Node value was updated.
/// </summary>
Update = 1,
/// <summary>
/// Node was inserted.
/// </summary>
Insert = 2,
/// <summary>
/// Node was deleted.
/// </summary>
Delete = 3,
}
private class LCS<T> : LongestCommonSubsequence<IList<T>>
{
public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default);
private readonly IEqualityComparer<T> _comparer;
public LCS(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB)
{
return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]);
}
public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString)
{
foreach (var edit in GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse())
{
switch (edit.Kind)
{
case EditKind.Delete:
yield return "--> " + toString(sequenceA[edit.IndexA]);
break;
case EditKind.Insert:
yield return "++> " + toString(sequenceB[edit.IndexB]);
break;
case EditKind.Update:
yield return " " + toString(sequenceB[edit.IndexB]);
break;
}
}
}
}
public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, string separator, IEqualityComparer<T> comparer = null, Func<T, string> toString = null)
{
var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default;
toString = toString ?? new Func<T, string>(obj => obj.ToString());
IList<T> expectedList = expected as IList<T> ?? new List<T>(expected);
IList<T> actualList = actual as IList<T> ?? new List<T>(actual);
return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString));
}
private static readonly char[] s_lineSplitChars = new[] { '\r', '\n' };
public static string[] Lines(string s)
{
return s.Split(s_lineSplitChars, StringSplitOptions.RemoveEmptyEntries);
}
public static string DiffReport(string expected, string actual)
{
var exlines = Lines(expected);
var aclines = Lines(actual);
return DiffReport(exlines, aclines, separator: Environment.NewLine);
}
/// <summary>
/// Calculates Longest Common Subsequence.
/// </summary>
private abstract class LongestCommonSubsequence<TSequence>
{
protected struct Edit
{
public readonly EditKind Kind;
public readonly int IndexA;
public readonly int IndexB;
internal Edit(EditKind kind, int indexA, int indexB)
{
this.Kind = kind;
this.IndexA = indexA;
this.IndexB = indexB;
}
}
private const int DeleteCost = 1;
private const int InsertCost = 1;
private const int UpdateCost = 2;
protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
}
else
{
i--;
j--;
yield return new KeyValuePair<int, int>(i, j);
}
}
}
protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
else
{
i--;
j--;
yield return new Edit(EditKind.Update, i, j);
}
}
while (i > 0)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
while (j > 0)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
}
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
Debug.Assert(lengthA >= 0 && lengthB >= 0);
if (lengthA == 0 || lengthB == 0)
{
return (lengthA == lengthB) ? 0.0 : 1.0;
}
int lcsLength = 0;
foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB))
{
lcsLength++;
}
int max = Math.Max(lengthA, lengthB);
Debug.Assert(lcsLength <= max);
return 1.0 - (double)lcsLength / (double)max;
}
/// <summary>
/// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB).
/// </summary>
/// <remarks>
/// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB].
///
/// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph.
/// Horizontal edges connect each vertex to its right neighbor.
/// Vertical edges connect each vertex to the neighbor below it.
/// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true.
///
/// Editing starts with S = [].
/// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S.
/// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S.
/// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable
/// change of sequenceA[i-1] to sequenceB[j-1].
///
/// In every vertex the cheapest outgoing edge is selected.
/// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence.
/// </remarks>
private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
var la = lengthA + 1;
var lb = lengthB + 1;
// TODO: Optimization possible: O(ND) time, O(N) space
// EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations
var d = new int[la, lb];
d[0, 0] = 0;
for (int i = 1; i <= lengthA; i++)
{
d[i, 0] = d[i - 1, 0] + DeleteCost;
}
for (int j = 1; j <= lengthB; j++)
{
d[0, j] = d[0, j - 1] + InsertCost;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost);
int m2 = d[i - 1, j] + DeleteCost;
int m3 = d[i, j - 1] + InsertCost;
d[i, j] = Math.Min(Math.Min(m1, m2), m3);
}
}
return d;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class DiffUtil
{
private enum EditKind
{
/// <summary>
/// No change.
/// </summary>
None = 0,
/// <summary>
/// Node value was updated.
/// </summary>
Update = 1,
/// <summary>
/// Node was inserted.
/// </summary>
Insert = 2,
/// <summary>
/// Node was deleted.
/// </summary>
Delete = 3,
}
private class LCS<T> : LongestCommonSubsequence<IList<T>>
{
public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default);
private readonly IEqualityComparer<T> _comparer;
public LCS(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB)
{
return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]);
}
public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString)
{
foreach (var edit in GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse())
{
switch (edit.Kind)
{
case EditKind.Delete:
yield return "--> " + toString(sequenceA[edit.IndexA]);
break;
case EditKind.Insert:
yield return "++> " + toString(sequenceB[edit.IndexB]);
break;
case EditKind.Update:
yield return " " + toString(sequenceB[edit.IndexB]);
break;
}
}
}
}
public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, string separator, IEqualityComparer<T> comparer = null, Func<T, string> toString = null)
{
var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default;
toString = toString ?? new Func<T, string>(obj => obj.ToString());
IList<T> expectedList = expected as IList<T> ?? new List<T>(expected);
IList<T> actualList = actual as IList<T> ?? new List<T>(actual);
return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString));
}
private static readonly char[] s_lineSplitChars = new[] { '\r', '\n' };
public static string[] Lines(string s)
{
return s.Split(s_lineSplitChars, StringSplitOptions.RemoveEmptyEntries);
}
public static string DiffReport(string expected, string actual)
{
var exlines = Lines(expected);
var aclines = Lines(actual);
return DiffReport(exlines, aclines, separator: Environment.NewLine);
}
/// <summary>
/// Calculates Longest Common Subsequence.
/// </summary>
private abstract class LongestCommonSubsequence<TSequence>
{
protected struct Edit
{
public readonly EditKind Kind;
public readonly int IndexA;
public readonly int IndexB;
internal Edit(EditKind kind, int indexA, int indexB)
{
this.Kind = kind;
this.IndexA = indexA;
this.IndexB = indexB;
}
}
private const int DeleteCost = 1;
private const int InsertCost = 1;
private const int UpdateCost = 2;
protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
}
else
{
i--;
j--;
yield return new KeyValuePair<int, int>(i, j);
}
}
}
protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
else
{
i--;
j--;
yield return new Edit(EditKind.Update, i, j);
}
}
while (i > 0)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
while (j > 0)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
}
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
Debug.Assert(lengthA >= 0 && lengthB >= 0);
if (lengthA == 0 || lengthB == 0)
{
return (lengthA == lengthB) ? 0.0 : 1.0;
}
int lcsLength = 0;
foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB))
{
lcsLength++;
}
int max = Math.Max(lengthA, lengthB);
Debug.Assert(lcsLength <= max);
return 1.0 - (double)lcsLength / (double)max;
}
/// <summary>
/// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB).
/// </summary>
/// <remarks>
/// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB].
///
/// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph.
/// Horizontal edges connect each vertex to its right neighbor.
/// Vertical edges connect each vertex to the neighbor below it.
/// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true.
///
/// Editing starts with S = [].
/// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S.
/// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S.
/// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable
/// change of sequenceA[i-1] to sequenceB[j-1].
///
/// In every vertex the cheapest outgoing edge is selected.
/// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence.
/// </remarks>
private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
var la = lengthA + 1;
var lb = lengthB + 1;
// TODO: Optimization possible: O(ND) time, O(N) space
// EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations
var d = new int[la, lb];
d[0, 0] = 0;
for (int i = 1; i <= lengthA; i++)
{
d[i, 0] = d[i - 1, 0] + DeleteCost;
}
for (int j = 1; j <= lengthB; j++)
{
d[0, j] = d[0, j - 1] + InsertCost;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost);
int m2 = d[i - 1, j] + DeleteCost;
int m3 = d[i, j - 1] + InsertCost;
d[i, j] = Math.Min(Math.Min(m1, m2), m3);
}
}
return d;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Portable/BoundTree/BoundNullCoalescingAssignmentOperator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundNullCoalescingAssignmentOperator
{
internal bool IsNullableValueTypeAssignment
{
get
{
var leftType = LeftOperand.Type;
if (leftType?.IsNullableType() != true)
{
return false;
}
var nullableUnderlying = leftType.GetNullableUnderlyingType();
return nullableUnderlying.Equals(RightOperand.Type);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundNullCoalescingAssignmentOperator
{
internal bool IsNullableValueTypeAssignment
{
get
{
var leftType = LeftOperand.Type;
if (leftType?.IsNullableType() != true)
{
return false;
}
var nullableUnderlying = leftType.GetNullableUnderlyingType();
return nullableUnderlying.Equals(RightOperand.Type);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.ExtractMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.ExtractMethod;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int ExtractMethod_AllowBestEffort
{
get { return GetBooleanOption(ExtractMethodOptions.AllowBestEffort); }
set { SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value); }
}
public int ExtractMethod_DoNotPutOutOrRefOnStruct
{
get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); }
set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.ExtractMethod;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int ExtractMethod_AllowBestEffort
{
get { return GetBooleanOption(ExtractMethodOptions.AllowBestEffort); }
set { SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value); }
}
public int ExtractMethod_DoNotPutOutOrRefOnStruct
{
get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); }
set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); }
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/TreeType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class TreeType
{
[XmlAttribute]
public string Name;
[XmlAttribute]
public string Base;
[XmlAttribute]
public string SkipConvenienceFactories;
[XmlElement]
public Comment TypeComment;
[XmlElement]
public Comment FactoryComment;
[XmlElement(ElementName = "Field", Type = typeof(Field))]
[XmlElement(ElementName = "Choice", Type = typeof(Choice))]
[XmlElement(ElementName = "Sequence", Type = typeof(Sequence))]
public List<TreeTypeChild> Children = new List<TreeTypeChild>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class TreeType
{
[XmlAttribute]
public string Name;
[XmlAttribute]
public string Base;
[XmlAttribute]
public string SkipConvenienceFactories;
[XmlElement]
public Comment TypeComment;
[XmlElement]
public Comment FactoryComment;
[XmlElement(ElementName = "Field", Type = typeof(Field))]
[XmlElement(ElementName = "Choice", Type = typeof(Choice))]
[XmlElement(ElementName = "Sequence", Type = typeof(Sequence))]
public List<TreeTypeChild> Children = new List<TreeTypeChild>();
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/LocalFunctions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class LocalFunctions : FlowTestBase
{
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void UncalledLambdaInLocalFunction()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L()
{
Action a = () =>
{
int x;
x++;
};
}
}
}");
comp.VerifyDiagnostics(
// (12,17): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 17),
// (7,14): warning CS8321: The local function 'L' is declared but never used
// void L()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void LambdaInNestedUncalledLocalFunctions()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L1()
{
void L2()
{
Action a = () =>
{
int x;
x++;
};
}
L2();
}
}
}");
comp.VerifyDiagnostics(
// (14,21): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(14, 21),
// (7,14): warning CS8321: The local function 'L1' is declared but never used
// void L1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L1").WithArguments("L1").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void CapturedInLambdaInUncalledLocalFunction()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L()
{
int x;
Action f = () => x++;
}
}
}");
comp.VerifyDiagnostics(
// (10,30): error CS0165: Use of unassigned local variable 'x'
// Action f = () => x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(10, 30),
// (7,14): warning CS8321: The local function 'L' is declared but never used
// void L()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void CapturedInNestedUncalledLocalFunctions()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void L1()
{
int x;
void L2() => x++;
}
}
}");
comp.VerifyDiagnostics(
// (9,18): warning CS8321: The local function 'L2' is declared but never used
// void L2() => x++;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(9, 18),
// (6,14): warning CS8321: The local function 'L1' is declared but never used
// void L1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L1").WithArguments("L1").WithLocation(6, 14));
}
[Fact]
public void ConstUnassigned()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
int L()
{
int y = x + 1;
const int x = 0;
return y;
}
}
}");
comp.VerifyDiagnostics(
// (9,21): error CS0841: Cannot use local variable 'x' before it is declared
// int y = x + 1;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(9, 21));
}
[Fact]
public void ConstUnassigned2()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
int L() => x;
const int x = 0;
}
}");
comp.VerifyDiagnostics(
// (7,20): error CS0841: Cannot use local variable 'x' before it is declared
// int L() => x;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(7, 20));
}
[Fact]
public void ConstUnassigned3()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
const int x;
int L() => x;
}
}");
comp.VerifyDiagnostics(
// (7,19): error CS0145: A const field requires a value to be provided
// const int x;
Diagnostic(ErrorCode.ERR_ConstValueRequired, "x").WithLocation(7, 19));
}
[Fact]
[WorkItem(14243, "https://github.com/dotnet/roslyn/issues/14243")]
public void AssignInsideCallToLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
int Local(int p1) => x++;
Local(x = 0);
int z;
int Local2(int p1, int p2) => z++;
Local2(z = 0, z++);
}
public void M2()
{
int x;
int Local(int p1) => x++;
int Local2(int p1) => Local(p1);
int Local3(int p1) => x + Local2(p1);
Local3(x = 0);
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14046, "https://github.com/dotnet/roslyn/issues/14046")]
public void UnreachableAfterThrow()
{
var comp = CreateCompilation(@"
class C
{
public void M3()
{
int x, y;
void Local()
{
throw null;
x = 5; // unreachable code
System.Console.WriteLine(y);
}
Local();
System.Console.WriteLine(x);
System.Console.WriteLine(y);
}
}");
comp.VerifyDiagnostics(
// (10,7): warning CS0162: Unreachable code detected
// x = 5; // unreachable code
Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(10, 7));
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void UnreachableRecursion()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x, y;
void Local()
{
Local();
x = 0;
}
Local();
x++;
y++;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadBeforeUnreachable()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
void Local()
{
x++;
Local();
}
Local();
x++;
}
}");
comp.VerifyDiagnostics(
// (12,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(12, 9));
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void MutualRecursiveUnreachable()
{
var comp = CreateCompilation(@"
class C
{
public static void M()
{
int x, y, z;
void L1()
{
L2();
x++; // Unreachable
}
void L2()
{
L1();
y++; // Unreachable
}
L1();
// Unreachable code, so everything should be definitely assigned
x++;
y++;
z++;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void AssignedInDeadBranch()
{
var comp = CreateCompilation(@"
using System;
class Program
{
public static void Main(string[] args)
{
int u;
M();
https://github.com/dotnet/roslyn/issues/13739
Console.WriteLine(u); // error: use of unassigned local variable 'u'
return;
void M()
{
goto La;
Lb: return;
La: u = 3;
goto Lb;
}
}
}");
comp.VerifyDiagnostics(
// (10,5): warning CS0164: This label has not been referenced
// https://github.com/dotnet/roslyn/issues/13739
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "https").WithLocation(10, 5));
}
[Fact]
public void InvalidBranchOutOfLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void M()
{
label1:
L();
L2();
L3();
void L()
{
goto label1;
}
void L2()
{
break;
}
void L3()
{
continue;
}
}
}");
comp.VerifyDiagnostics(
// (19,13): error CS0139: No enclosing loop out of which to break or continue
// break;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(19, 13),
// (24,13): error CS0139: No enclosing loop out of which to break or continue
// continue;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(24, 13),
// (14,13): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label1").WithLocation(14, 13));
}
[Fact]
[WorkItem(13762, "https://github.com/dotnet/roslyn/issues/13762")]
public void AssignsInAsync()
{
var comp = CreateCompilationWithMscorlib46(@"
using System.Threading.Tasks;
class C
{
public static void M2()
{
int a=0, x, y, z;
L1();
a++;
x++;
y++;
z++;
async void L1()
{
x = 0;
await Task.Delay(0);
y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (12,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(12, 9),
// (13,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(13, 9));
}
[Fact]
[WorkItem(13762, "https://github.com/dotnet/roslyn/issues/13762")]
public void AssignsInIterator()
{
var comp = CreateCompilationWithMscorlib46(@"
using System.Collections.Generic;
class C
{
public static void M2()
{
int a=0, w, x, y, z;
L1();
a++;
w++;
x++;
y++;
z++;
IEnumerable<bool> L1()
{
w = 0;
yield return false;
x = 0;
yield break;
y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (24,13): warning CS0162: Unreachable code detected
// y = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "y").WithLocation(24, 13),
// (13,9): error CS0165: Use of unassigned local variable 'w'
// w++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(13, 9),
// (14,9): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(14, 9),
// (15,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(15, 9),
// (16,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(16, 9));
}
[Fact]
public void SimpleForwardCall()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
var x = Local();
int Local() => 2;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void DefinedWhenCalled()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
x = 0;
Local();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void NotDefinedWhenCalled()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (8,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(8, 9)
);
}
[Fact]
public void ChainedDef()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local2() => Local1();
bool Local1() => x == 0;
Local2();
}
}");
comp.VerifyDiagnostics(
// (9,9): error CS0165: Use of unassigned local variable 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x").WithLocation(9, 9)
);
}
[Fact]
public void SetInLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
void L1()
{
x = 0;
}
bool L2() => x == 0;
L1();
L2();
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void SetInLocalFuncMutual()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool L1()
{
L2();
return x == 0;
}
void L2()
{
x = 0;
L1();
}
L1();
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void LongWriteChain()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
bool L1()
{
L2();
return x == 0;
}
bool L2()
{
L3();
return x == 0;
}
bool L3()
{
L4();
return x == 0;
}
void L4()
{
x = 0;
}
L1();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ConvertBeforeDefined()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool L1() => x == 0;
System.Func<bool> f = L1;
x = 0;
f();
}
}");
comp.VerifyDiagnostics(
// (8,31): error CS0165: Use of unassigned local variable 'x'
// System.Func<bool> f = L1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "L1").WithArguments("x").WithLocation(8, 31));
}
[Fact]
public void NestedCapture()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
void Local1()
{
int x;
bool Local2() => x == 0;
Local2();
}
Local1();
}
}");
comp.VerifyDiagnostics(
// (10,13): error CS0165: Use of unassigned local variable 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x").WithLocation(10, 13));
}
[Fact]
public void UnusedLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
}
}");
comp.VerifyDiagnostics(
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// bool Local() => x == 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
}
[Fact]
public void UnassignedInStruct()
{
var comp = CreateCompilation(@"
struct S
{
int _x;
public S(int x)
{
var s = this;
void Local()
{
s._x = _x;
}
Local();
}
}");
comp.VerifyDiagnostics(
// (10,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// s._x = _x;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "_x").WithLocation(10, 20),
// (7,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to
// var s = this;
Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(7, 17),
// (12,9): error CS0170: Use of possibly unassigned field '_x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("_x").WithLocation(12, 9),
// (5,12): error CS0171: Field 'S._x' must be fully assigned before control is returned to the caller
// public S(int x)
Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S._x").WithLocation(5, 12));
}
[Fact]
public void AssignWithStruct()
{
var comp = CreateCompilation(@"
struct S
{
public int x;
public int y;
}
class C
{
public void M1()
{
S s1;
Local();
S s2 = s1; // unassigned
void Local()
{
s1.x = 0;
}
s1.y = 0;
}
public void M2()
{
S s1;
Local();
S s2 = s1; // success
void Local()
{
s1.x = 0;
s1.y = 0;
}
}
public void M3()
{
S s1;
S s2 = s1; // unassigned
Local();
void Local()
{
s1.x = 0;
s1.y = 0;
}
}
void M4()
{
S s1;
Local();
void Local()
{
s1.x = 0;
s1.x += s1.y;
}
}
}");
comp.VerifyDiagnostics(
// (14,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(14, 16),
// (37,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(37, 16),
// (48,9): error CS0170: Use of possibly unassigned field 'y'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("y").WithLocation(48, 9));
}
[Fact]
public void NestedStructProperty()
{
var comp = CreateCompilation(@"
struct A
{
public int x;
public int y { get; set; }
}
struct B
{
public A a;
public int z;
}
class C
{
void AssignInLocalFunc()
{
A a1;
Local1(); // unassigned
A a2 = a1;
void Local1()
{
a1.x = 0;
a1.y = 0;
}
B b1;
Local2();
B b2 = b1;
void Local2()
{
b1.a.x = 0;
b1.a.y = 0;
b1.z = 0;
}
}
void SkipNestedField()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.a.x = 0;
b1.z = 0;
}
}
void SkipNestedStruct()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.z = 0;
}
}
void SkipField()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.a.x = 0;
b1.a.y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (19,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local1(); // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local1()").WithArguments("y").WithLocation(19, 9),
// (28,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local2()").WithArguments("y").WithLocation(28, 9),
// (41,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(41, 16),
// (52,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(52, 16),
// (61,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local()").WithArguments("y").WithLocation(61, 9),
// (62,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(62, 16));
}
[Fact]
public void WriteAndReadInLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
bool b;
Local();
void Local()
{
x = x + 1;
x = 0;
}
b = x == 0;
}
}");
comp.VerifyDiagnostics(
// (8,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(8, 9));
}
[Fact]
public void EventReadAndWrite()
{
var comp = CreateCompilation(@"
using System;
struct S
{
public int x;
public event EventHandler Event;
public void Fire() => Event(null, EventArgs.Empty);
}
class C
{
void PartialAssign()
{
S s1;
Local1();
S s2 = s1;
void Local1()
{
s1.x = 0;
}
}
void FullAssign()
{
S s1;
Local1();
S s2 = s1;
void Local1()
{
s1 = new S();
s1.x = 0;
s1.Event += Handler1;
s1.Fire();
void Handler1(object sender, EventArgs args)
{
s1.x++;
}
}
S s3;
void Local2()
{
s3.x = 0;
s3.Event += Handler2;
void Handler2(object sender, EventArgs args)
{
s1.x++;
s3.x++;
}
}
S s4 = s3;
Local2();
}
}");
comp.VerifyDiagnostics(
// (18,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(18, 16),
// (54,16): error CS0165: Use of unassigned local variable 's3'
// S s4 = s3;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s3").WithArguments("s3").WithLocation(54, 16),
// (55,9): error CS0170: Use of possibly unassigned field 'Event'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local2()").WithArguments("Event").WithLocation(55, 9));
}
[Fact]
public void CaptureForeachVar()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
var items = new[] { 0, 1, 2, 3};
foreach (var i in items)
{
void Local()
{
i = 4;
}
Local();
}
}
}");
comp.VerifyDiagnostics(
// (11,17): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable'
// i = 4;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(11, 17));
}
[Fact]
public void CapturePattern()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
object o = 2;
if (o is int x1 && Local(x1) == 0)
{
}
if (o is int x2 || Local(x2) == 0)
{
}
if (!(o is int x3))
{
void Local2()
{
x3++;
}
Local2();
}
int Local(int i) => i;
}
}");
comp.VerifyDiagnostics(
// (11,34): error CS0165: Use of unassigned local variable 'x2'
// if (o is int x2 || Local(x2) == 0)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(11, 34),
// (21,13): error CS0165: Use of unassigned local variable 'x3'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x3").WithLocation(21, 13));
}
[Fact]
public void NotAssignedControlFlow()
{
var comp = CreateCompilation(@"
class C
{
void FullyAssigned()
{
int x;
int y = 0;
void Local()
{
if (y == 0)
x = 0;
else
Local2();
}
void Local2()
{
x = 0;
}
Local();
y = x;
}
void PartiallyAssigned()
{
int x;
int y = 0;
void Local()
{
if (y == 0)
x = 0;
else
Local2();
}
void Local2()
{
//x = 0;
}
Local();
y = x; // unassigned
}
}");
comp.VerifyDiagnostics(
// (38,13): error CS0165: Use of unassigned local variable 'x'
// y = x; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(38, 13));
}
[Fact]
public void UseConsts()
{
var comp = CreateCompilation(@"
struct S
{
public const int z = 0;
}
class C
{
const int x = 0;
void M()
{
const int y = 0;
Local();
int Local()
{
const int a = 1;
return a + x + y + S.z;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void NotAssignedAtAllReturns()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
void L1()
{
if ("""".Length == 1)
{
x = 1;
}
else
{
return;
}
}
L1();
var z = x;
}
}");
comp.VerifyDiagnostics(
// (19,17): error CS0165: Use of unassigned local variable 'x'
// var z = x;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(19, 17));
}
[Fact]
public void NotAssignedAtThrow()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x1, x2;
void L1()
{
if ("""".Length == 1)
x1 = x2 = 0;
else
throw new System.Exception();
}
try
{
L1();
var y = x1;
}
catch
{
var z = x1;
}
var zz = x2;
}
}");
comp.VerifyDiagnostics(
// (21,21): error CS0165: Use of unassigned local variable 'x1'
// var z = x1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 21),
// (23,18): error CS0165: Use of unassigned local variable 'x2'
// var zz = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(23, 18));
}
[Fact]
public void DeadCode()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
goto live;
void L1() => x = 0;
live:
L1();
var z = x;
}
void M2()
{
int x;
goto live;
void L1()
{
if ("""".Length == 1)
x = 0;
else
return;
}
live:
L1();
var z = x;
}
}");
comp.VerifyDiagnostics(
// (26,17): error CS0165: Use of unassigned local variable 'x'
// var z = x;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(26, 17));
}
[Fact]
public void LocalFunctionFromOtherSwitch()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
int y;
switch("""".Length)
{
case 0:
void L1()
{
y = 0;
L2();
}
break;
case 1:
L1();
y = x;
break;
case 2:
void L2()
{
x = y;
}
break;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(15298, "https://github.com/dotnet/roslyn/issues/15298")]
public void UnassignedUndefinedVariable()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
{
Goo();
int x = 0;
void Goo() => x++;
}
{
System.Action a = Goo;
int x = 0;
void Goo() => x++;
}
}
}");
comp.VerifyDiagnostics(
// (7,13): error CS0165: Use of unassigned local variable 'x'
// Goo();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo()").WithArguments("x").WithLocation(7, 13),
// (12,31): error CS0165: Use of unassigned local variable 'x'
// System.Action a = Goo;
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo").WithArguments("x").WithLocation(12, 31));
}
[Fact]
[WorkItem(15322, "https://github.com/dotnet/roslyn/issues/15322")]
public void UseBeforeDeclarationInSwitch()
{
var comp = CreateCompilation(@"
class Program
{
static void Main(object[] args)
{
switch(args[0])
{
case string x:
Goo();
break;
case int x:
void Goo() => System.Console.WriteLine(x);
break;
}
}
}");
comp.VerifyDiagnostics(
// (9,17): error CS0165: Use of unassigned local variable 'x'
// Goo();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo()").WithArguments("x").WithLocation(9, 17));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign()
{
var comp = CreateCompilation(@"
struct S { public int X, Y; }
class C
{
public static void Main()
{
S s;
s.X = 5;
void Local()
{
s.Y = 10;
System.Console.WriteLine(s);
}
Local();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign2()
{
var comp = CreateCompilation(@"
struct S
{
public int X;
public int Y { get; set; }
public S(int x, int y)
{
this.X = x;
this.Y = y;
Local(this);
void Local(S s)
{
s.X++;
s.Y++;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign3()
{
var comp = CreateCompilation(@"
struct S { }
struct S2
{
public int x;
public S s;
}
class C
{
public void M()
{
S2 s2;
void Local1()
{
s2.x = 0;
S2 s4 = s2;
}
Local1();
S2 s3 = s2;
}
public void M2()
{
S2 s3;
void Local2()
{
s3.s = new S();
S2 s4 = s3;
}
Local2();
}
public void M3()
{
S2 s5;
void Local3()
{
s5.s = new S();
}
Local3();
S2 s6 = s5;
}
}");
comp.VerifyDiagnostics(
// (30,9): error CS0170: Use of possibly unassigned field 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local2()").WithArguments("x").WithLocation(30, 9),
// (41,17): error CS0165: Use of unassigned local variable 's5'
// S2 s6 = s5;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s5").WithArguments("s5").WithLocation(41, 17));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssignmentInConstructor()
{
var comp = CreateCompilation(@"
struct S
{
public int _x;
public int _y;
public S(int x, int y)
{
_y = 0;
void Local()
{
_x = 0;
S s2 = this;
}
Local();
}
}");
// Note that definite assignment is still validated in this
// compilation
comp.VerifyDiagnostics(
// (12,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// _x = 0;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "_x").WithLocation(12, 13),
// (13,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// S s2 = this;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(13, 20));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssignmentInConstructor2()
{
var comp = CreateCompilation(@"
struct S
{
public int _x;
public int _y;
public S(int x, int y)
{
_y = 0;
void Local()
{
S s2 = this;
}
Local();
_x = 0;
}
}");
comp.VerifyDiagnostics(
// (12,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// S s2 = this;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(12, 20),
// (14,9): error CS0170: Use of possibly unassigned field '_x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("_x").WithLocation(14, 9));
}
[Fact]
[WorkItem(18813, "https://github.com/dotnet/roslyn/issues/18813")]
public void LocalIEnumerableFunctionWithOutParameter1()
{
var comp = CreateCompilation(@"
class c
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool output)
{
output = true;
yield return ""goo"";
}
getGoo(1, out bool myBool);
}
}");
comp.VerifyDiagnostics(
// (6,83): error CS1623: Iterators cannot have ref, in or out parameters
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "output"),
// (6,56): error CS0177: The out parameter 'goobar' must be assigned to before control leaves the current method
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "getGoo").WithArguments("output").WithLocation(6, 56));
}
[Fact]
[WorkItem(18813, "https://github.com/dotnet/roslyn/issues/18813")]
public void LocalIEnumerableFunctionWithOutParameter2()
{
var comp = CreateCompilation(@"
class c
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool output)
{
output = false;
for (int i = 0; i < count; i++)
{
foreach (var val in getGoo(3, out var bar))
yield return ""goo"";
}
yield return ""goo"";
}
getGoo(1, out bool myBool);
}
}");
comp.VerifyDiagnostics(
// (6,83): error CS1623: Iterators cannot have ref, in or out parameters
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "output"),
// (6,56): error CS0177: The out parameter 'goobar' must be assigned to before control leaves the current method
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "getGoo").WithArguments("output").WithLocation(6, 56));
}
[Fact]
[WorkItem(41631, "https://github.com/dotnet/roslyn/issues/41631")]
public void UseOfCapturedVariableAssignedByOutParameter()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(out s0); // 1
void local1(out string s1)
{
s0.ToString();
s1 = ""hello"";
}
}
}").VerifyDiagnostics(
// (7,9): error CS0165: Use of unassigned local variable 's0'
// local1(out s0);
Diagnostic(ErrorCode.ERR_UseDefViolation, "local1(out s0)").WithArguments("s0").WithLocation(7, 9));
}
[Fact]
public void OutParameterIsAssignedByLocalFunction()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(out s0);
s0.ToString();
void local1(out string s1)
{
s1 = ""hello"";
}
}
}").VerifyDiagnostics();
}
[Fact]
public void UseOfCapturedVariableAssignedInArgument()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(s0 = ""hello"", out s0);
void local1(string s1, out string s2)
{
s0.ToString();
s2 = ""bye"";
}
}
}").VerifyDiagnostics();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class LocalFunctions : FlowTestBase
{
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void UncalledLambdaInLocalFunction()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L()
{
Action a = () =>
{
int x;
x++;
};
}
}
}");
comp.VerifyDiagnostics(
// (12,17): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 17),
// (7,14): warning CS8321: The local function 'L' is declared but never used
// void L()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void LambdaInNestedUncalledLocalFunctions()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L1()
{
void L2()
{
Action a = () =>
{
int x;
x++;
};
}
L2();
}
}
}");
comp.VerifyDiagnostics(
// (14,21): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(14, 21),
// (7,14): warning CS8321: The local function 'L1' is declared but never used
// void L1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L1").WithArguments("L1").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void CapturedInLambdaInUncalledLocalFunction()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
void L()
{
int x;
Action f = () => x++;
}
}
}");
comp.VerifyDiagnostics(
// (10,30): error CS0165: Use of unassigned local variable 'x'
// Action f = () => x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(10, 30),
// (7,14): warning CS8321: The local function 'L' is declared but never used
// void L()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(7, 14));
}
[Fact]
[WorkItem(17829, "https://github.com/dotnet/roslyn/issues/17829")]
public void CapturedInNestedUncalledLocalFunctions()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void L1()
{
int x;
void L2() => x++;
}
}
}");
comp.VerifyDiagnostics(
// (9,18): warning CS8321: The local function 'L2' is declared but never used
// void L2() => x++;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(9, 18),
// (6,14): warning CS8321: The local function 'L1' is declared but never used
// void L1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L1").WithArguments("L1").WithLocation(6, 14));
}
[Fact]
public void ConstUnassigned()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
int L()
{
int y = x + 1;
const int x = 0;
return y;
}
}
}");
comp.VerifyDiagnostics(
// (9,21): error CS0841: Cannot use local variable 'x' before it is declared
// int y = x + 1;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(9, 21));
}
[Fact]
public void ConstUnassigned2()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
int L() => x;
const int x = 0;
}
}");
comp.VerifyDiagnostics(
// (7,20): error CS0841: Cannot use local variable 'x' before it is declared
// int L() => x;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(7, 20));
}
[Fact]
public void ConstUnassigned3()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
L();
const int x;
int L() => x;
}
}");
comp.VerifyDiagnostics(
// (7,19): error CS0145: A const field requires a value to be provided
// const int x;
Diagnostic(ErrorCode.ERR_ConstValueRequired, "x").WithLocation(7, 19));
}
[Fact]
[WorkItem(14243, "https://github.com/dotnet/roslyn/issues/14243")]
public void AssignInsideCallToLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
int Local(int p1) => x++;
Local(x = 0);
int z;
int Local2(int p1, int p2) => z++;
Local2(z = 0, z++);
}
public void M2()
{
int x;
int Local(int p1) => x++;
int Local2(int p1) => Local(p1);
int Local3(int p1) => x + Local2(p1);
Local3(x = 0);
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14046, "https://github.com/dotnet/roslyn/issues/14046")]
public void UnreachableAfterThrow()
{
var comp = CreateCompilation(@"
class C
{
public void M3()
{
int x, y;
void Local()
{
throw null;
x = 5; // unreachable code
System.Console.WriteLine(y);
}
Local();
System.Console.WriteLine(x);
System.Console.WriteLine(y);
}
}");
comp.VerifyDiagnostics(
// (10,7): warning CS0162: Unreachable code detected
// x = 5; // unreachable code
Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(10, 7));
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void UnreachableRecursion()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x, y;
void Local()
{
Local();
x = 0;
}
Local();
x++;
y++;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadBeforeUnreachable()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
void Local()
{
x++;
Local();
}
Local();
x++;
}
}");
comp.VerifyDiagnostics(
// (12,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(12, 9));
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void MutualRecursiveUnreachable()
{
var comp = CreateCompilation(@"
class C
{
public static void M()
{
int x, y, z;
void L1()
{
L2();
x++; // Unreachable
}
void L2()
{
L1();
y++; // Unreachable
}
L1();
// Unreachable code, so everything should be definitely assigned
x++;
y++;
z++;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(13739, "https://github.com/dotnet/roslyn/issues/13739")]
public void AssignedInDeadBranch()
{
var comp = CreateCompilation(@"
using System;
class Program
{
public static void Main(string[] args)
{
int u;
M();
https://github.com/dotnet/roslyn/issues/13739
Console.WriteLine(u); // error: use of unassigned local variable 'u'
return;
void M()
{
goto La;
Lb: return;
La: u = 3;
goto Lb;
}
}
}");
comp.VerifyDiagnostics(
// (10,5): warning CS0164: This label has not been referenced
// https://github.com/dotnet/roslyn/issues/13739
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "https").WithLocation(10, 5));
}
[Fact]
public void InvalidBranchOutOfLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void M()
{
label1:
L();
L2();
L3();
void L()
{
goto label1;
}
void L2()
{
break;
}
void L3()
{
continue;
}
}
}");
comp.VerifyDiagnostics(
// (19,13): error CS0139: No enclosing loop out of which to break or continue
// break;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(19, 13),
// (24,13): error CS0139: No enclosing loop out of which to break or continue
// continue;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(24, 13),
// (14,13): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label1").WithLocation(14, 13));
}
[Fact]
[WorkItem(13762, "https://github.com/dotnet/roslyn/issues/13762")]
public void AssignsInAsync()
{
var comp = CreateCompilationWithMscorlib46(@"
using System.Threading.Tasks;
class C
{
public static void M2()
{
int a=0, x, y, z;
L1();
a++;
x++;
y++;
z++;
async void L1()
{
x = 0;
await Task.Delay(0);
y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (12,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(12, 9),
// (13,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(13, 9));
}
[Fact]
[WorkItem(13762, "https://github.com/dotnet/roslyn/issues/13762")]
public void AssignsInIterator()
{
var comp = CreateCompilationWithMscorlib46(@"
using System.Collections.Generic;
class C
{
public static void M2()
{
int a=0, w, x, y, z;
L1();
a++;
w++;
x++;
y++;
z++;
IEnumerable<bool> L1()
{
w = 0;
yield return false;
x = 0;
yield break;
y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (24,13): warning CS0162: Unreachable code detected
// y = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "y").WithLocation(24, 13),
// (13,9): error CS0165: Use of unassigned local variable 'w'
// w++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(13, 9),
// (14,9): error CS0165: Use of unassigned local variable 'x'
// x++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(14, 9),
// (15,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(15, 9),
// (16,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(16, 9));
}
[Fact]
public void SimpleForwardCall()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
var x = Local();
int Local() => 2;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void DefinedWhenCalled()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
x = 0;
Local();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void NotDefinedWhenCalled()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (8,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(8, 9)
);
}
[Fact]
public void ChainedDef()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local2() => Local1();
bool Local1() => x == 0;
Local2();
}
}");
comp.VerifyDiagnostics(
// (9,9): error CS0165: Use of unassigned local variable 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x").WithLocation(9, 9)
);
}
[Fact]
public void SetInLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
void L1()
{
x = 0;
}
bool L2() => x == 0;
L1();
L2();
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void SetInLocalFuncMutual()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool L1()
{
L2();
return x == 0;
}
void L2()
{
x = 0;
L1();
}
L1();
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void LongWriteChain()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
bool L1()
{
L2();
return x == 0;
}
bool L2()
{
L3();
return x == 0;
}
bool L3()
{
L4();
return x == 0;
}
void L4()
{
x = 0;
}
L1();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ConvertBeforeDefined()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool L1() => x == 0;
System.Func<bool> f = L1;
x = 0;
f();
}
}");
comp.VerifyDiagnostics(
// (8,31): error CS0165: Use of unassigned local variable 'x'
// System.Func<bool> f = L1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "L1").WithArguments("x").WithLocation(8, 31));
}
[Fact]
public void NestedCapture()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
void Local1()
{
int x;
bool Local2() => x == 0;
Local2();
}
Local1();
}
}");
comp.VerifyDiagnostics(
// (10,13): error CS0165: Use of unassigned local variable 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x").WithLocation(10, 13));
}
[Fact]
public void UnusedLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int x;
bool Local() => x == 0;
}
}");
comp.VerifyDiagnostics(
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// bool Local() => x == 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
}
[Fact]
public void UnassignedInStruct()
{
var comp = CreateCompilation(@"
struct S
{
int _x;
public S(int x)
{
var s = this;
void Local()
{
s._x = _x;
}
Local();
}
}");
comp.VerifyDiagnostics(
// (10,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// s._x = _x;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "_x").WithLocation(10, 20),
// (7,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to
// var s = this;
Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(7, 17),
// (12,9): error CS0170: Use of possibly unassigned field '_x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("_x").WithLocation(12, 9),
// (5,12): error CS0171: Field 'S._x' must be fully assigned before control is returned to the caller
// public S(int x)
Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S._x").WithLocation(5, 12));
}
[Fact]
public void AssignWithStruct()
{
var comp = CreateCompilation(@"
struct S
{
public int x;
public int y;
}
class C
{
public void M1()
{
S s1;
Local();
S s2 = s1; // unassigned
void Local()
{
s1.x = 0;
}
s1.y = 0;
}
public void M2()
{
S s1;
Local();
S s2 = s1; // success
void Local()
{
s1.x = 0;
s1.y = 0;
}
}
public void M3()
{
S s1;
S s2 = s1; // unassigned
Local();
void Local()
{
s1.x = 0;
s1.y = 0;
}
}
void M4()
{
S s1;
Local();
void Local()
{
s1.x = 0;
s1.x += s1.y;
}
}
}");
comp.VerifyDiagnostics(
// (14,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(14, 16),
// (37,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(37, 16),
// (48,9): error CS0170: Use of possibly unassigned field 'y'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("y").WithLocation(48, 9));
}
[Fact]
public void NestedStructProperty()
{
var comp = CreateCompilation(@"
struct A
{
public int x;
public int y { get; set; }
}
struct B
{
public A a;
public int z;
}
class C
{
void AssignInLocalFunc()
{
A a1;
Local1(); // unassigned
A a2 = a1;
void Local1()
{
a1.x = 0;
a1.y = 0;
}
B b1;
Local2();
B b2 = b1;
void Local2()
{
b1.a.x = 0;
b1.a.y = 0;
b1.z = 0;
}
}
void SkipNestedField()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.a.x = 0;
b1.z = 0;
}
}
void SkipNestedStruct()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.z = 0;
}
}
void SkipField()
{
B b1;
Local();
B b2 = b1; // unassigned
void Local()
{
b1.a.x = 0;
b1.a.y = 0;
}
}
}");
comp.VerifyDiagnostics(
// (19,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local1(); // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local1()").WithArguments("y").WithLocation(19, 9),
// (28,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local2()").WithArguments("y").WithLocation(28, 9),
// (41,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(41, 16),
// (52,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(52, 16),
// (61,9): error CS8079: Use of possibly unassigned auto-implemented property 'y'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "Local()").WithArguments("y").WithLocation(61, 9),
// (62,16): error CS0165: Use of unassigned local variable 'b1'
// B b2 = b1; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "b1").WithArguments("b1").WithLocation(62, 16));
}
[Fact]
public void WriteAndReadInLocalFunc()
{
var comp = CreateCompilation(@"
class C
{
public void M()
{
int x;
bool b;
Local();
void Local()
{
x = x + 1;
x = 0;
}
b = x == 0;
}
}");
comp.VerifyDiagnostics(
// (8,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(8, 9));
}
[Fact]
public void EventReadAndWrite()
{
var comp = CreateCompilation(@"
using System;
struct S
{
public int x;
public event EventHandler Event;
public void Fire() => Event(null, EventArgs.Empty);
}
class C
{
void PartialAssign()
{
S s1;
Local1();
S s2 = s1;
void Local1()
{
s1.x = 0;
}
}
void FullAssign()
{
S s1;
Local1();
S s2 = s1;
void Local1()
{
s1 = new S();
s1.x = 0;
s1.Event += Handler1;
s1.Fire();
void Handler1(object sender, EventArgs args)
{
s1.x++;
}
}
S s3;
void Local2()
{
s3.x = 0;
s3.Event += Handler2;
void Handler2(object sender, EventArgs args)
{
s1.x++;
s3.x++;
}
}
S s4 = s3;
Local2();
}
}");
comp.VerifyDiagnostics(
// (18,16): error CS0165: Use of unassigned local variable 's1'
// S s2 = s1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s1").WithArguments("s1").WithLocation(18, 16),
// (54,16): error CS0165: Use of unassigned local variable 's3'
// S s4 = s3;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s3").WithArguments("s3").WithLocation(54, 16),
// (55,9): error CS0170: Use of possibly unassigned field 'Event'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local2()").WithArguments("Event").WithLocation(55, 9));
}
[Fact]
public void CaptureForeachVar()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
var items = new[] { 0, 1, 2, 3};
foreach (var i in items)
{
void Local()
{
i = 4;
}
Local();
}
}
}");
comp.VerifyDiagnostics(
// (11,17): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable'
// i = 4;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(11, 17));
}
[Fact]
public void CapturePattern()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
object o = 2;
if (o is int x1 && Local(x1) == 0)
{
}
if (o is int x2 || Local(x2) == 0)
{
}
if (!(o is int x3))
{
void Local2()
{
x3++;
}
Local2();
}
int Local(int i) => i;
}
}");
comp.VerifyDiagnostics(
// (11,34): error CS0165: Use of unassigned local variable 'x2'
// if (o is int x2 || Local(x2) == 0)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(11, 34),
// (21,13): error CS0165: Use of unassigned local variable 'x3'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local2()").WithArguments("x3").WithLocation(21, 13));
}
[Fact]
public void NotAssignedControlFlow()
{
var comp = CreateCompilation(@"
class C
{
void FullyAssigned()
{
int x;
int y = 0;
void Local()
{
if (y == 0)
x = 0;
else
Local2();
}
void Local2()
{
x = 0;
}
Local();
y = x;
}
void PartiallyAssigned()
{
int x;
int y = 0;
void Local()
{
if (y == 0)
x = 0;
else
Local2();
}
void Local2()
{
//x = 0;
}
Local();
y = x; // unassigned
}
}");
comp.VerifyDiagnostics(
// (38,13): error CS0165: Use of unassigned local variable 'x'
// y = x; // unassigned
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(38, 13));
}
[Fact]
public void UseConsts()
{
var comp = CreateCompilation(@"
struct S
{
public const int z = 0;
}
class C
{
const int x = 0;
void M()
{
const int y = 0;
Local();
int Local()
{
const int a = 1;
return a + x + y + S.z;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void NotAssignedAtAllReturns()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
void L1()
{
if ("""".Length == 1)
{
x = 1;
}
else
{
return;
}
}
L1();
var z = x;
}
}");
comp.VerifyDiagnostics(
// (19,17): error CS0165: Use of unassigned local variable 'x'
// var z = x;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(19, 17));
}
[Fact]
public void NotAssignedAtThrow()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x1, x2;
void L1()
{
if ("""".Length == 1)
x1 = x2 = 0;
else
throw new System.Exception();
}
try
{
L1();
var y = x1;
}
catch
{
var z = x1;
}
var zz = x2;
}
}");
comp.VerifyDiagnostics(
// (21,21): error CS0165: Use of unassigned local variable 'x1'
// var z = x1;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 21),
// (23,18): error CS0165: Use of unassigned local variable 'x2'
// var zz = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(23, 18));
}
[Fact]
public void DeadCode()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
goto live;
void L1() => x = 0;
live:
L1();
var z = x;
}
void M2()
{
int x;
goto live;
void L1()
{
if ("""".Length == 1)
x = 0;
else
return;
}
live:
L1();
var z = x;
}
}");
comp.VerifyDiagnostics(
// (26,17): error CS0165: Use of unassigned local variable 'x'
// var z = x;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(26, 17));
}
[Fact]
public void LocalFunctionFromOtherSwitch()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int x;
int y;
switch("""".Length)
{
case 0:
void L1()
{
y = 0;
L2();
}
break;
case 1:
L1();
y = x;
break;
case 2:
void L2()
{
x = y;
}
break;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(15298, "https://github.com/dotnet/roslyn/issues/15298")]
public void UnassignedUndefinedVariable()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
{
Goo();
int x = 0;
void Goo() => x++;
}
{
System.Action a = Goo;
int x = 0;
void Goo() => x++;
}
}
}");
comp.VerifyDiagnostics(
// (7,13): error CS0165: Use of unassigned local variable 'x'
// Goo();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo()").WithArguments("x").WithLocation(7, 13),
// (12,31): error CS0165: Use of unassigned local variable 'x'
// System.Action a = Goo;
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo").WithArguments("x").WithLocation(12, 31));
}
[Fact]
[WorkItem(15322, "https://github.com/dotnet/roslyn/issues/15322")]
public void UseBeforeDeclarationInSwitch()
{
var comp = CreateCompilation(@"
class Program
{
static void Main(object[] args)
{
switch(args[0])
{
case string x:
Goo();
break;
case int x:
void Goo() => System.Console.WriteLine(x);
break;
}
}
}");
comp.VerifyDiagnostics(
// (9,17): error CS0165: Use of unassigned local variable 'x'
// Goo();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Goo()").WithArguments("x").WithLocation(9, 17));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign()
{
var comp = CreateCompilation(@"
struct S { public int X, Y; }
class C
{
public static void Main()
{
S s;
s.X = 5;
void Local()
{
s.Y = 10;
System.Console.WriteLine(s);
}
Local();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign2()
{
var comp = CreateCompilation(@"
struct S
{
public int X;
public int Y { get; set; }
public S(int x, int y)
{
this.X = x;
this.Y = y;
Local(this);
void Local(S s)
{
s.X++;
s.Y++;
}
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssign3()
{
var comp = CreateCompilation(@"
struct S { }
struct S2
{
public int x;
public S s;
}
class C
{
public void M()
{
S2 s2;
void Local1()
{
s2.x = 0;
S2 s4 = s2;
}
Local1();
S2 s3 = s2;
}
public void M2()
{
S2 s3;
void Local2()
{
s3.s = new S();
S2 s4 = s3;
}
Local2();
}
public void M3()
{
S2 s5;
void Local3()
{
s5.s = new S();
}
Local3();
S2 s6 = s5;
}
}");
comp.VerifyDiagnostics(
// (30,9): error CS0170: Use of possibly unassigned field 'x'
// Local2();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local2()").WithArguments("x").WithLocation(30, 9),
// (41,17): error CS0165: Use of unassigned local variable 's5'
// S2 s6 = s5;
Diagnostic(ErrorCode.ERR_UseDefViolation, "s5").WithArguments("s5").WithLocation(41, 17));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssignmentInConstructor()
{
var comp = CreateCompilation(@"
struct S
{
public int _x;
public int _y;
public S(int x, int y)
{
_y = 0;
void Local()
{
_x = 0;
S s2 = this;
}
Local();
}
}");
// Note that definite assignment is still validated in this
// compilation
comp.VerifyDiagnostics(
// (12,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// _x = 0;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "_x").WithLocation(12, 13),
// (13,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// S s2 = this;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(13, 20));
}
[Fact]
[WorkItem(14097, "https://github.com/dotnet/roslyn/issues/14097")]
public void PiecewiseStructAssignmentInConstructor2()
{
var comp = CreateCompilation(@"
struct S
{
public int _x;
public int _y;
public S(int x, int y)
{
_y = 0;
void Local()
{
S s2 = this;
}
Local();
_x = 0;
}
}");
comp.VerifyDiagnostics(
// (12,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// S s2 = this;
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(12, 20),
// (14,9): error CS0170: Use of possibly unassigned field '_x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolationField, "Local()").WithArguments("_x").WithLocation(14, 9));
}
[Fact]
[WorkItem(18813, "https://github.com/dotnet/roslyn/issues/18813")]
public void LocalIEnumerableFunctionWithOutParameter1()
{
var comp = CreateCompilation(@"
class c
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool output)
{
output = true;
yield return ""goo"";
}
getGoo(1, out bool myBool);
}
}");
comp.VerifyDiagnostics(
// (6,83): error CS1623: Iterators cannot have ref, in or out parameters
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "output"),
// (6,56): error CS0177: The out parameter 'goobar' must be assigned to before control leaves the current method
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "getGoo").WithArguments("output").WithLocation(6, 56));
}
[Fact]
[WorkItem(18813, "https://github.com/dotnet/roslyn/issues/18813")]
public void LocalIEnumerableFunctionWithOutParameter2()
{
var comp = CreateCompilation(@"
class c
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool output)
{
output = false;
for (int i = 0; i < count; i++)
{
foreach (var val in getGoo(3, out var bar))
yield return ""goo"";
}
yield return ""goo"";
}
getGoo(1, out bool myBool);
}
}");
comp.VerifyDiagnostics(
// (6,83): error CS1623: Iterators cannot have ref, in or out parameters
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "output"),
// (6,56): error CS0177: The out parameter 'goobar' must be assigned to before control leaves the current method
// System.Collections.Generic.IEnumerable<string> getGoo(int count, out bool goobar)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "getGoo").WithArguments("output").WithLocation(6, 56));
}
[Fact]
[WorkItem(41631, "https://github.com/dotnet/roslyn/issues/41631")]
public void UseOfCapturedVariableAssignedByOutParameter()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(out s0); // 1
void local1(out string s1)
{
s0.ToString();
s1 = ""hello"";
}
}
}").VerifyDiagnostics(
// (7,9): error CS0165: Use of unassigned local variable 's0'
// local1(out s0);
Diagnostic(ErrorCode.ERR_UseDefViolation, "local1(out s0)").WithArguments("s0").WithLocation(7, 9));
}
[Fact]
public void OutParameterIsAssignedByLocalFunction()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(out s0);
s0.ToString();
void local1(out string s1)
{
s1 = ""hello"";
}
}
}").VerifyDiagnostics();
}
[Fact]
public void UseOfCapturedVariableAssignedInArgument()
{
CreateCompilation(@"
public class C
{
void M()
{
string s0;
local1(s0 = ""hello"", out s0);
void local1(string s1, out string s2)
{
s0.ToString();
s2 = ""bye"";
}
}
}").VerifyDiagnostics();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/VisualBasic/Portable/Structure/Providers/SyncLockBlockStructureProvider.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.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class SyncLockBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of SyncLockBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As SyncLockBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.SyncLockStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class SyncLockBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of SyncLockBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As SyncLockBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.SyncLockStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure
{
public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests
{
internal abstract AbstractSyntaxStructureProvider CreateProvider();
internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position)
{
var root = await document.GetSyntaxRootAsync();
var trivia = root.FindTrivia(position, findInsideTrivia: true);
var outliner = CreateProvider();
using var actualRegions = TemporaryArray<BlockSpan>.Empty;
var optionProvider = new BlockStructureOptionProvider(
document.Project.Solution.Options,
isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource);
outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None);
// TODO: Determine why we get null outlining spans.
return actualRegions.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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure
{
public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests
{
internal abstract AbstractSyntaxStructureProvider CreateProvider();
internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position)
{
var root = await document.GetSyntaxRootAsync();
var trivia = root.FindTrivia(position, findInsideTrivia: true);
var outliner = CreateProvider();
using var actualRegions = TemporaryArray<BlockSpan>.Empty;
var optionProvider = new BlockStructureOptionProvider(
document.Project.Solution.Options,
isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource);
outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None);
// TODO: Determine why we get null outlining spans.
return actualRegions.ToImmutableAndClear();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/VisualBasicTest/ConvertAnonymousTypeToClass/ConvertAnonymousTypeToClassTests.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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertAnonymousTypeToClass
Public Class ConvertAnonymousTypeToClassTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertAnonymousTypeToClassCodeRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertSingleAnonymousType() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnEmptyAnonymousType() As Task
Await TestInRegularAndScriptAsync("
class Test
sub Method()
dim t1 = [||]new with { }
end sub
end class
",
"
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}()
end sub
end class
Friend Class NewClass
Public Sub New()
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing
End Function
Public Overrides Function GetHashCode() As Integer
Return 0
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnSingleFieldAnonymousType() As Task
Await TestInRegularAndScriptAsync("
class Test
sub Method()
dim t1 = [||]new with { key .a = 1 }
end sub
end class
",
"
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public Sub New(a As Integer)
Me.A = a
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Dim hashCode As Long = -1005848884
hashCode = (hashCode * -1521134295 + A.GetHashCode()).GetHashCode()
Return hashCode
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertSingleAnonymousTypeWithInferredName() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key b }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, b)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleInstancesInSameMethod() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleInstancesAcrossMethods() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnlyConvertMatchingTypesInSameMethod() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key b }
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, b)
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestFixAllMatchesInSingleMethod() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key b }
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, b)
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestFixNotAcrossMethods() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function NotIfReferencesAnonymousTypeInternally() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = new with { key .c = 1, key .d = 2 } }
end sub
end class
"
Await TestMissingInRegularAndScriptAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleNestedInstancesInSameMethod() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = directcast(new with { key .a = 1, key .b = directcast(nothing, object) }, object) }
end sub
end class
"
Dim expected = "
Imports System.Collections.Generic
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, directcast(New NewClass(1, directcast(nothing, object)), object))
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Object
Public Sub New(a As Integer, b As Object)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
EqualityComparer(Of Object).Default.Equals(B, other.B)
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function RenameAnnotationOnStartingPoint() As Task
Dim text = "
class Test
sub Method()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = [||]new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New NewClass(1, 2)
dim t2 = New {|Rename:NewClass|}(3, 4)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function UpdateReferences() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
Console.WriteLine(t1.a + t1?.b)
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
Console.WriteLine(t1.A + t1?.B)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function CapturedTypeParameters() As Task
Dim text = "
imports System.Collections.Generic
class Test(of X as {structure})
sub Method(of Y as {class, new})(lst as List(of X), arr as Y())
dim t1 = [||]new with { key .a = lst, key .b = arr }
end sub
end class
"
Dim expected = "
imports System.Collections.Generic
class Test(of X as {structure})
sub Method(of Y as {class, new})(lst as List(of X), arr as Y())
dim t1 = New {|Rename:NewClass|}(Of X, Y)(lst, arr)
end sub
end class
Friend Class NewClass(Of X As Structure, Y As {Class, New})
Public ReadOnly Property A As List(Of X)
Public ReadOnly Property B As Y()
Public Sub New(a As List(Of X), b() As Y)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass(Of X, Y))
Return other IsNot Nothing AndAlso
EqualityComparer(Of List(Of X)).Default.Equals(A, other.A) AndAlso
EqualityComparer(Of Y()).Default.Equals(B, other.B)
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestNonKeyProperties() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, .b = 2 }
dim t2 = new with { key .a = 3, .b = 4 }
dim t3 = new with { key .a = 3, key .b = 4 }
dim t4 = new with { .a = 3, key .b = 4 }
dim t5 = new with { .a = 3, .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
dim t3 = new with { key .a = 3, key .b = 4 }
dim t4 = new with { .a = 3, key .b = 4 }
dim t5 = new with { .a = 3, .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Dim hashCode As Long = -1005848884
hashCode = (hashCode * -1521134295 + A.GetHashCode()).GetHashCode()
Return hashCode
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestNameCollision() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
end sub
end class
class newclass
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass1|}(1, 2)
end sub
end class
class newclass
end class
Friend Class NewClass1
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass1)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestDuplicatedName() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .a = 2 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property A As Integer
Public Sub New(a As Integer, a As Integer)
Me.A = a
Me.A = a
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
Me.A = other.A AndAlso
Me.A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Return (Me.A, Me.A).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertAnonymousTypeToClass
Public Class ConvertAnonymousTypeToClassTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertAnonymousTypeToClassCodeRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertSingleAnonymousType() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnEmptyAnonymousType() As Task
Await TestInRegularAndScriptAsync("
class Test
sub Method()
dim t1 = [||]new with { }
end sub
end class
",
"
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}()
end sub
end class
Friend Class NewClass
Public Sub New()
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing
End Function
Public Overrides Function GetHashCode() As Integer
Return 0
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnSingleFieldAnonymousType() As Task
Await TestInRegularAndScriptAsync("
class Test
sub Method()
dim t1 = [||]new with { key .a = 1 }
end sub
end class
",
"
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public Sub New(a As Integer)
Me.A = a
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Dim hashCode As Long = -1005848884
hashCode = (hashCode * -1521134295 + A.GetHashCode()).GetHashCode()
Return hashCode
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertSingleAnonymousTypeWithInferredName() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key b }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, b)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleInstancesInSameMethod() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleInstancesAcrossMethods() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function OnlyConvertMatchingTypesInSameMethod() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key b }
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, b)
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestFixAllMatchesInSingleMethod() As Task
Dim text = "
class Test
sub Method(b as integer)
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key b }
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
"
Dim expected = "
class Test
sub Method(b as integer)
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, b)
dim t3 = new with { key .a = 4 }
dim t4 = new with { key .b = 5, key .a = 6 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestFixNotAcrossMethods() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
end sub
sub Method2()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = new with { key .a = 3, key .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function NotIfReferencesAnonymousTypeInternally() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = new with { key .c = 1, key .d = 2 } }
end sub
end class
"
Await TestMissingInRegularAndScriptAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function ConvertMultipleNestedInstancesInSameMethod() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = directcast(new with { key .a = 1, key .b = directcast(nothing, object) }, object) }
end sub
end class
"
Dim expected = "
Imports System.Collections.Generic
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, directcast(New NewClass(1, directcast(nothing, object)), object))
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Object
Public Sub New(a As Integer, b As Object)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
EqualityComparer(Of Object).Default.Equals(B, other.B)
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function RenameAnnotationOnStartingPoint() As Task
Dim text = "
class Test
sub Method()
dim t1 = new with { key .a = 1, key .b = 2 }
dim t2 = [||]new with { key .a = 3, key .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New NewClass(1, 2)
dim t2 = New {|Rename:NewClass|}(3, 4)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function UpdateReferences() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
Console.WriteLine(t1.a + t1?.b)
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
Console.WriteLine(t1.A + t1?.B)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function CapturedTypeParameters() As Task
Dim text = "
imports System.Collections.Generic
class Test(of X as {structure})
sub Method(of Y as {class, new})(lst as List(of X), arr as Y())
dim t1 = [||]new with { key .a = lst, key .b = arr }
end sub
end class
"
Dim expected = "
imports System.Collections.Generic
class Test(of X as {structure})
sub Method(of Y as {class, new})(lst as List(of X), arr as Y())
dim t1 = New {|Rename:NewClass|}(Of X, Y)(lst, arr)
end sub
end class
Friend Class NewClass(Of X As Structure, Y As {Class, New})
Public ReadOnly Property A As List(Of X)
Public ReadOnly Property B As Y()
Public Sub New(a As List(Of X), b() As Y)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass(Of X, Y))
Return other IsNot Nothing AndAlso
EqualityComparer(Of List(Of X)).Default.Equals(A, other.A) AndAlso
EqualityComparer(Of Y()).Default.Equals(B, other.B)
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestNonKeyProperties() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, .b = 2 }
dim t2 = new with { key .a = 3, .b = 4 }
dim t3 = new with { key .a = 3, key .b = 4 }
dim t4 = new with { .a = 3, key .b = 4 }
dim t5 = new with { .a = 3, .b = 4 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
dim t2 = New NewClass(3, 4)
dim t3 = new with { key .a = 3, key .b = 4 }
dim t4 = new with { .a = 3, key .b = 4 }
dim t5 = new with { .a = 3, .b = 4 }
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Dim hashCode As Long = -1005848884
hashCode = (hashCode * -1521134295 + A.GetHashCode()).GetHashCode()
Return hashCode
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestNameCollision() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .b = 2 }
end sub
end class
class newclass
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass1|}(1, 2)
end sub
end class
class newclass
end class
Friend Class NewClass1
Public ReadOnly Property A As Integer
Public ReadOnly Property B As Integer
Public Sub New(a As Integer, b As Integer)
Me.A = a
Me.B = b
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass1)
Return other IsNot Nothing AndAlso
A = other.A AndAlso
B = other.B
End Function
Public Overrides Function GetHashCode() As Integer
Return (A, B).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)>
Public Async Function TestDuplicatedName() As Task
Dim text = "
class Test
sub Method()
dim t1 = [||]new with { key .a = 1, key .a = 2 }
end sub
end class
"
Dim expected = "
class Test
sub Method()
dim t1 = New {|Rename:NewClass|}(1, 2)
end sub
end class
Friend Class NewClass
Public ReadOnly Property A As Integer
Public ReadOnly Property A As Integer
Public Sub New(a As Integer, a As Integer)
Me.A = a
Me.A = a
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, NewClass)
Return other IsNot Nothing AndAlso
Me.A = other.A AndAlso
Me.A = other.A
End Function
Public Overrides Function GetHashCode() As Integer
Return (Me.A, Me.A).GetHashCode()
End Function
End Class
"
Await TestInRegularAndScriptAsync(text, expected)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.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
<ExportSignatureHelpProvider("AddRemoveHandlerSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Friend Class AddRemoveHandlerSignatureHelpProvider
Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of AddRemoveHandlerStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As AddRemoveHandlerStatementSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Select Case node.Kind
Case SyntaxKind.AddHandlerStatement
Return ValueTaskFactory.FromResult(SpecializedCollections.SingletonEnumerable(Of AbstractIntrinsicOperatorDocumentation)(New AddHandlerStatementDocumentation()))
Case SyntaxKind.RemoveHandlerStatement
Return ValueTaskFactory.FromResult(SpecializedCollections.SingletonEnumerable(Of AbstractIntrinsicOperatorDocumentation)(New RemoveHandlerStatementDocumentation()))
End Select
Return ValueTaskFactory.FromResult(SpecializedCollections.EmptyEnumerable(Of AbstractIntrinsicOperatorDocumentation)())
End Function
Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean
Return token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.AddHandlerOrRemoveHandlerKeyword) OrElse
token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.CommaToken)
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 False
End Function
Protected Overrides Function IsArgumentListToken(node As AddRemoveHandlerStatementSyntax, token As SyntaxToken) As Boolean
Return True
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("AddRemoveHandlerSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Friend Class AddRemoveHandlerSignatureHelpProvider
Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of AddRemoveHandlerStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As AddRemoveHandlerStatementSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Select Case node.Kind
Case SyntaxKind.AddHandlerStatement
Return ValueTaskFactory.FromResult(SpecializedCollections.SingletonEnumerable(Of AbstractIntrinsicOperatorDocumentation)(New AddHandlerStatementDocumentation()))
Case SyntaxKind.RemoveHandlerStatement
Return ValueTaskFactory.FromResult(SpecializedCollections.SingletonEnumerable(Of AbstractIntrinsicOperatorDocumentation)(New RemoveHandlerStatementDocumentation()))
End Select
Return ValueTaskFactory.FromResult(SpecializedCollections.EmptyEnumerable(Of AbstractIntrinsicOperatorDocumentation)())
End Function
Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean
Return token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.AddHandlerOrRemoveHandlerKeyword) OrElse
token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.CommaToken)
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 False
End Function
Protected Overrides Function IsArgumentListToken(node As AddRemoveHandlerStatementSyntax, token As SyntaxToken) As Boolean
Return True
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler
{
[UseExportProvider]
public class WorkCoordinatorTests : TestBase
{
private const string SolutionCrawlerWorkspaceKind = "SolutionCrawler";
[Fact]
public async Task RegisterService()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
Assert.Empty(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider>());
var registrationService = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
// register and unregister workspace to the service
registrationService.Register(workspace);
registrationService.Unregister(workspace);
// make sure we wait for all waiter. the test wrongly assumed there won't be
// any pending async event which is implementation detail when creating workspace
// and changing options.
await WaitWaiterAsync(workspace.ExportProvider);
}
[Fact]
public async Task DynamicallyAddAnalyzer()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
// create solution and wait for it to settle
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
// create solution crawler and add new analyzer provider dynamically
Assert.Empty(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider>());
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var worker = new Analyzer();
var provider = new AnalyzerProvider(worker);
service.AddAnalyzerProvider(provider, Metadata.Crawler);
// wait for everything to settle
await WaitAsync(service, workspace);
service.Unregister(workspace);
// check whether everything ran as expected
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory, WorkItem(747226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747226")]
internal async Task SolutionAdded_Simple(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionId = SolutionId.CreateNewId();
var projectId = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
})
});
var expectedDocumentEvents = 1;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task SolutionAdded_Complex(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
var expectedDocumentEvents = 10;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Remove(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Clear(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.ClearSolution());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Reload(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentEvents = 10;
var expectedProjectEvents = 2;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution));
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(expectedProjectEvents, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Change(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.First().DocumentIds[0];
solution = solution.RemoveDocument(documentId);
var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution;
var expectedDocumentEvents = 1;
var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Add(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new List<DocumentInfo>
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2")
});
var expectedDocumentEvents = 2;
var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Remove(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var projectid = workspace.CurrentSolution.ProjectIds[0];
var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Change(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First();
var documentId = project.DocumentIds[0];
var solution = workspace.CurrentSolution.RemoveDocument(documentId);
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_AssemblyName_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.WithAssemblyName("newName");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_DefaultNamespace_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.WithDefaultNamespace("newNamespace");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_AnalyzerOptions_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.AddAdditionalDocument("a1", SourceText.From("")).Project;
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_OutputFilePath_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectOutputFilePath(project.Id, "/newPath");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_OutputRefFilePath_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectOutputRefFilePath(project.Id, "/newPath");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_CompilationOutputInfo_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectCompilationOutputInfo(project.Id, new CompilationOutputInfo(assemblyPath: "/newPath"));
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_RunAnalyzers_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
Assert.True(project.State.RunAnalyzers);
var newSolution = workspace.CurrentSolution.WithRunAnalyzers(project.Id, false);
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
project = workspace.CurrentSolution.GetProject(project.Id);
Assert.False(project.State.RunAnalyzers);
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[Fact]
public async Task Test_NeedsReanalysisOnOptionChanged()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(Analyzer.TestOption, false))));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[Fact]
public async Task Test_BackgroundAnalysisScopeOptionChanged_ActiveFile()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
MakeFirstDocumentActive(workspace.CurrentSolution.Projects.First());
await WaitWaiterAsync(workspace.ExportProvider);
Assert.Equal(BackgroundAnalysisScope.Default, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
var newAnalysisScope = BackgroundAnalysisScope.ActiveFile;
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, newAnalysisScope))));
Assert.Equal(newAnalysisScope, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[Fact]
public async Task Test_BackgroundAnalysisScopeOptionChanged_FullSolution()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
Assert.Equal(BackgroundAnalysisScope.Default, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
var newAnalysisScope = BackgroundAnalysisScope.FullSolution;
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, newAnalysisScope))));
Assert.Equal(newAnalysisScope, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Reload(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentEvents = 5;
var expectedProjectEvents = 1;
var project = solution.Projects[0];
var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project));
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(expectedProjectEvents, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Add(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = await ExecuteOperation(workspace, w =>
{
w.OnDocumentAdded(info);
if (activeDocument)
{
var document = w.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
});
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 6;
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Remove(BackgroundAnalysisScope analysisScope, bool removeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (removeActiveDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(document.Id));
var expectedDocumentInvalidatedEvents = 1;
var expectedDocumentSyntaxEvents = 0;
var expectedDocumentSemanticEvents = 4;
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
Assert.Equal(expectedDocumentInvalidatedEvents, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Reload(BackgroundAnalysisScope analysisScope, bool reloadActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var info = solution.Projects[0].Documents[0];
if (reloadActiveDocument)
{
var document = workspace.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(info));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(0, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Reanalyze(BackgroundAnalysisScope analysisScope, bool reanalyzeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var info = solution.Projects[0].Documents[0];
if (reanalyzeActiveDocument)
{
var document = workspace.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(worker.WaitForCancellation);
Assert.False(worker.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
await TouchEverything(workspace.CurrentSolution);
service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable(info.Id), highPriority: false);
await TouchEverything(workspace.CurrentSolution);
await WaitAsync(service, workspace);
service.Unregister(workspace);
var expectedReanalyzeDocumentCount = 1;
Assert.Equal(expectedReanalyzeDocumentCount, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedReanalyzeDocumentCount, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Change(BackgroundAnalysisScope analysisScope, bool changeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (changeActiveDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(document.Id, SourceText.From("//")));
var expectedDocumentEvents = 1;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_AdditionalFileChange(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var project = workspace.CurrentSolution.Projects.First();
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 5;
var expectedDocumentSemanticEvents = 5;
var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_AnalyzerConfigFileChange(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var project = workspace.CurrentSolution.Projects.First();
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 5;
var expectedDocumentSemanticEvents = 5;
var analyzerConfigDocFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(Temp.CreateDirectory().Path, ".editorconfig");
var analyzerConfigFile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), ".editorconfig", filePath: analyzerConfigDocFilePath);
var worker = await ExecuteOperation(workspace, w => w.OnAnalyzerConfigDocumentAdded(analyzerConfigFile));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.ChangeAnalyzerConfigDocument(analyzerConfigFile.Id, SourceText.From("//")));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.OnAnalyzerConfigDocumentRemoved(analyzerConfigFile.Id));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Cancellation(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (activeDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.True(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 5;
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
workspace.ChangeDocument(document.Id, SourceText.From("//"));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
}
token.Dispose();
workspace.ChangeDocument(document.Id, SourceText.From("// "));
await WaitAsync(service, workspace);
await expeditedWait;
service.Unregister(workspace);
Assert.Equal(expectedDocumentSyntaxEvents, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, analyzer.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Cancellation_MultipleTimes(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (activeDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 5;
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.True(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
workspace.ChangeDocument(document.Id, SourceText.From("//"));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
analyzer.RunningEvent.Reset();
}
workspace.ChangeDocument(document.Id, SourceText.From("// "));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
}
token.Dispose();
workspace.ChangeDocument(document.Id, SourceText.From("// "));
await WaitAsync(service, workspace);
await expeditedWait;
service.Unregister(workspace);
Assert.Equal(expectedDocumentSyntaxEvents, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, analyzer.DocumentIds.Count);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21082"), WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
public async Task Document_InvocationReasons()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(analyzer.WaitForCancellation);
Assert.True(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
// first invocation will block worker
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
var openReady = new ManualResetEventSlim(initialState: false);
var closeReady = new ManualResetEventSlim(initialState: false);
workspace.DocumentOpened += (o, e) => openReady.Set();
workspace.DocumentClosed += (o, e) => closeReady.Set();
// cause several different request to queue up
workspace.ChangeDocument(id, SourceText.From("// "));
workspace.OpenDocument(id);
workspace.CloseDocument(id);
openReady.Set();
closeReady.Set();
analyzer.BlockEvent.Set();
await WaitAsync(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_ActiveDocumentChanged(BackgroundAnalysisScope analysisScope, bool hasActiveDocumentBefore)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var documents = workspace.CurrentSolution.Projects.First().Documents.ToArray();
var firstDocument = documents[0];
var secondDocument = documents[1];
if (hasActiveDocumentBefore)
{
MakeDocumentActive(firstDocument);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedSyntaxDocumentEvents = (analysisScope, hasActiveDocumentBefore) switch
{
(BackgroundAnalysisScope.ActiveFile, _) => 1,
(BackgroundAnalysisScope.OpenFilesAndProjects or BackgroundAnalysisScope.FullSolution, _) => 0,
_ => throw ExceptionUtilities.Unreachable,
};
var expectedDocumentEvents = (analysisScope, hasActiveDocumentBefore) switch
{
(BackgroundAnalysisScope.ActiveFile, _) => 5,
(BackgroundAnalysisScope.OpenFilesAndProjects or BackgroundAnalysisScope.FullSolution, _) => 0,
_ => throw ExceptionUtilities.Unreachable,
};
// Switch to another active source document and verify expected document analysis callbacks
var worker = await ExecuteOperation(workspace, w => MakeDocumentActive(secondDocument));
Assert.Equal(expectedSyntaxDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
// Switch from an active source document to an active non-source document and verify no document analysis callbacks
worker = await ExecuteOperation(workspace, w => ClearActiveDocument(w));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(0, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
// Switch from an active non-source document to an active source document and verify document analysis callbacks
worker = await ExecuteOperation(workspace, w => MakeDocumentActive(firstDocument));
Assert.Equal(expectedSyntaxDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
}
[Fact]
public async Task Document_TopLevelType_Whitespace()
{
var code = @"class C { $$ }";
var textToInsert = " ";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_Character()
{
var code = @"class C { $$ }";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_NewLine()
{
var code = @"class C { $$ }";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_NewLine2()
{
var code = @"class C { $$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_EmptyFile()
{
var code = @"$$";
var textToInsert = "class";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel1()
{
var code = @"class C
{
public void Test($$";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel2()
{
var code = @"class C
{
public void Test(int $$";
var textToInsert = " ";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel3()
{
var code = @"class C
{
public void Test(int i,$$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_InteriorNode1()
{
var code = @"class C
{
public void Test()
{$$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode2()
{
var code = @"class C
{
public void Test()
{
$$
}";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Field()
{
var code = @"class C
{
int i = $$
}";
var textToInsert = "1";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Field1()
{
var code = @"class C
{
int i = 1 + $$
}";
var textToInsert = "1";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Accessor()
{
var code = @"class C
{
public int A
{
get
{
$$
}
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_TopLevelWhitespace()
{
var code = @"class C
{
/// $$
public int A()
{
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelWhitespace2()
{
var code = @"/// $$
class C
{
public int A()
{
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_InteriorNode_Malformed()
{
var code = @"class C
{
public void Test()
{
$$";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")]
public async Task SemanticChange_Propagation_Transitive()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, false)));
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
}
[Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")]
public async Task SemanticChange_Propagation_Direct()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, true)));
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(3, worker.DocumentIds.Count);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/23657")]
public async Task ProgressReporterTest()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
await WaitWaiterAsync(workspace.ExportProvider);
var service = workspace.Services.GetService<ISolutionCrawlerService>();
var reporter = service.GetProgressReporter(workspace);
Assert.False(reporter.InProgress);
// set up events
var started = false;
var stopped = false;
reporter.ProgressChanged += (o, s) =>
{
if (s.Status == ProgressStatus.Started)
{
started = true;
}
else if (s.Status == ProgressStatus.Stopped)
{
stopped = true;
}
};
var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();
registrationService.Register(workspace);
// first mutation
workspace.OnSolutionAdded(solution);
await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
// reset
started = false;
stopped = false;
// second mutation
workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6"));
await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
registrationService.Unregister(workspace);
}
[Fact]
[WorkItem(26244, "https://github.com/dotnet/roslyn/issues/26244")]
public async Task FileFromSameProjectTogetherTest()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: GetDocuments(projectId1, count: 5)),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: GetDocuments(projectId2, count: 5)),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: GetDocuments(projectId3, count: 5))
});
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProvider2));
await WaitWaiterAsync(workspace.ExportProvider);
// add analyzer
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer2>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
// enable solution crawler
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
await WaitWaiterAsync(workspace.ExportProvider);
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
// we want to test order items processed by solution crawler.
// but since everything async, lazy and cancellable, order is not 100% deterministic. an item might
// start to be processed, and get cancelled due to newly enqueued item requiring current work to be re-processed
// (ex, new file being added).
// this behavior is expected in real world, but it makes testing hard. so to make ordering deterministic
// here we first block solution crawler from processing any item using global operation.
// and then make sure all delayed work item enqueue to be done through waiters. work item enqueue is async
// and delayed since one of responsibility of solution cralwer is aggregating workspace events to fewer
// work items.
// once we are sure everything is stablized, we let solution crawler to process by releasing global operation.
// what this test is interested in is the order solution crawler process the pending works. so this should
// let the test not care about cancellation or work not enqueued yet.
// block solution cralwer from processing.
var globalOperation = workspace.Services.GetService<IGlobalOperationNotificationService>();
using (var operation = globalOperation.Start("Block SolutionCrawler"))
{
// make sure global operaiton is actually started
// otherwise, solution crawler might processed event we are later waiting for
var operationWaiter = GetListenerProvider(workspace.ExportProvider).GetWaiter(FeatureAttribute.GlobalOperation);
await operationWaiter.ExpeditedWaitAsync();
// mutate solution
workspace.OnSolutionAdded(solution);
// wait for workspace events to be all processed
var workspaceWaiter = GetListenerProvider(workspace.ExportProvider).GetWaiter(FeatureAttribute.Workspace);
await workspaceWaiter.ExpeditedWaitAsync();
// now wait for semantic processor to finish
var crawlerListener = (AsynchronousOperationListener)GetListenerProvider(workspace.ExportProvider).GetListener(FeatureAttribute.SolutionCrawler);
// first, wait for first work to be queued.
//
// since asyncToken doesn't distinguish whether (1) certain event is happened but all processed or (2) it never happened yet,
// to check (1), we must wait for first item, and then wait for all items to be processed.
await crawlerListener.WaitUntilConditionIsMetAsync(
pendingTokens => pendingTokens.Any(token => token.Tag == (object)SolutionCrawlerRegistrationService.EnqueueItem));
// and then wait them to be processed
await crawlerListener.WaitUntilConditionIsMetAsync(pendingTokens => pendingTokens.Where(token => token.Tag == workspace).IsEmpty());
// let analyzer to process
operation.Done();
}
token.Dispose();
// wait analyzers to finish process
await WaitAsync(service, workspace);
await expeditedWait;
Assert.Equal(1, worker.DocumentIds.Take(5).Select(d => d.ProjectId).Distinct().Count());
Assert.Equal(1, worker.DocumentIds.Skip(5).Take(5).Select(d => d.ProjectId).Distinct().Count());
Assert.Equal(1, worker.DocumentIds.Skip(10).Take(5).Select(d => d.ProjectId).Distinct().Count());
service.Unregister(workspace);
}
private static async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
{
using var workspace = TestWorkspace.Create(
language,
compilationOptions: null,
parseOptions: null,
new[] { code },
composition: EditorTestCompositions.EditorFeatures.AddExcludedPartTypes(typeof(IIncrementalAnalyzerProvider)).AddParts(typeof(AnalyzerProviderNoWaitNoBlock)),
workspaceKind: SolutionCrawlerWorkspaceKind);
var testDocument = workspace.Documents.First();
var textBuffer = testDocument.GetTextBuffer();
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var insertPosition = testDocument.CursorPosition;
using (var edit = textBuffer.CreateEdit())
{
edit.Insert(insertPosition.Value, text);
edit.Apply();
}
await WaitAsync(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
}
private static async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation)
{
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(worker.WaitForCancellation);
Assert.False(worker.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
worker.Reset();
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
await TouchEverything(workspace.CurrentSolution);
operation(workspace);
await TouchEverything(workspace.CurrentSolution);
await WaitAsync(service, workspace);
service.Unregister(workspace);
return worker;
}
private static async Task TouchEverything(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
await document.GetTextAsync();
await document.GetSyntaxRootAsync();
await document.GetSemanticModelAsync();
}
}
}
private static async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace)
{
await WaitWaiterAsync(workspace.ExportProvider);
service.GetTestAccessor().WaitUntilCompletion(workspace);
}
private static async Task WaitWaiterAsync(ExportProvider provider)
{
var workspaceWaiter = GetListenerProvider(provider).GetWaiter(FeatureAttribute.Workspace);
await workspaceWaiter.ExpeditedWaitAsync();
var solutionCrawlerWaiter = GetListenerProvider(provider).GetWaiter(FeatureAttribute.SolutionCrawler);
await solutionCrawlerWaiter.ExpeditedWaitAsync();
}
private static SolutionInfo GetInitialSolutionInfoWithP2P()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var projectId4 = ProjectId.CreateNewId();
var projectId5 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
projectReferences: new[] { new ProjectReference(projectId1) }),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
projectReferences: new[] { new ProjectReference(projectId2) }),
ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
projectReferences: new[] { new ProjectReference(projectId4) }),
});
return solution;
}
private static SolutionInfo GetInitialSolutionInfo_2Projects_10Documents()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: GetDocuments(projectId1, count: 5)),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: GetDocuments(projectId2, count: 5))
});
}
private static IEnumerable<DocumentInfo> GetDocuments(ProjectId projectId, int count)
{
for (var i = 0; i < count; i++)
{
yield return DocumentInfo.Create(DocumentId.CreateNewId(projectId), $"D{i + 1}");
}
}
private static AsynchronousOperationListenerProvider GetListenerProvider(ExportProvider provider)
=> provider.GetExportedValue<AsynchronousOperationListenerProvider>();
private static void MakeFirstDocumentActive(Project project)
=> MakeDocumentActive(project.Documents.First());
private static void MakeDocumentActive(Document document)
{
var documentTrackingService = (TestDocumentTrackingService)document.Project.Solution.Workspace.Services.GetRequiredService<IDocumentTrackingService>();
documentTrackingService.SetActiveDocument(document.Id);
}
private static void ClearActiveDocument(Workspace workspace)
{
var documentTrackingService = (TestDocumentTrackingService)workspace.Services.GetService<IDocumentTrackingService>();
documentTrackingService.SetActiveDocument(null);
}
private class WorkCoordinatorWorkspace : TestWorkspace
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestDocumentTrackingService)).AddExcludedPartTypes(typeof(IIncrementalAnalyzerProvider));
private readonly IAsynchronousOperationWaiter _workspaceWaiter;
private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter;
public WorkCoordinatorWorkspace(string workspaceKind = null, bool disablePartialSolutions = true, Type incrementalAnalyzer = null)
: base(composition: incrementalAnalyzer is null ? s_composition : s_composition.AddParts(incrementalAnalyzer), workspaceKind: workspaceKind, disablePartialSolutions: disablePartialSolutions)
{
_workspaceWaiter = GetListenerProvider(ExportProvider).GetWaiter(FeatureAttribute.Workspace);
_solutionCrawlerWaiter = GetListenerProvider(ExportProvider).GetWaiter(FeatureAttribute.SolutionCrawler);
Assert.False(_workspaceWaiter.HasPendingWork);
Assert.False(_solutionCrawlerWaiter.HasPendingWork);
}
public static WorkCoordinatorWorkspace CreateWithAnalysisScope(BackgroundAnalysisScope analysisScope, string workspaceKind = null, bool disablePartialSolutions = true, Type incrementalAnalyzer = null)
{
var workspace = new WorkCoordinatorWorkspace(workspaceKind, disablePartialSolutions, incrementalAnalyzer);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, analysisScope)));
return workspace;
}
protected override void Dispose(bool finalize)
{
base.Dispose(finalize);
Assert.False(_workspaceWaiter.HasPendingWork);
Assert.False(_solutionCrawlerWaiter.HasPendingWork);
}
}
private class AnalyzerProvider : IIncrementalAnalyzerProvider
{
public readonly IIncrementalAnalyzer Analyzer;
public AnalyzerProvider(IIncrementalAnalyzer analyzer)
=> Analyzer = analyzer;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
=> Analyzer;
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderNoWaitNoBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderNoWaitNoBlock()
: base(new Analyzer())
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderWaitNoBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderWaitNoBlock()
: base(new Analyzer(waitForCancellation: true))
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderNoWaitBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderNoWaitBlock()
: base(new Analyzer(blockedRun: true))
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProvider2 : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProvider2()
: base(new Analyzer2())
{
}
}
internal static class Metadata
{
public static readonly IncrementalAnalyzerProviderMetadata Crawler = new IncrementalAnalyzerProviderMetadata(new Dictionary<string, object> { { "WorkspaceKinds", new[] { SolutionCrawlerWorkspaceKind } }, { "HighPriorityForActiveFile", false }, { "Name", "TestAnalyzer" } });
}
private class Analyzer : IIncrementalAnalyzer
{
public static readonly Option<bool> TestOption = new Option<bool>("TestOptions", "TestOption", defaultValue: true);
public readonly ManualResetEventSlim BlockEvent;
public readonly ManualResetEventSlim RunningEvent;
public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>();
public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>();
public Analyzer(bool waitForCancellation = false, bool blockedRun = false)
{
WaitForCancellation = waitForCancellation;
BlockedRun = blockedRun;
this.BlockEvent = new ManualResetEventSlim(initialState: false);
this.RunningEvent = new ManualResetEventSlim(initialState: false);
}
public bool WaitForCancellation { get; }
public bool BlockedRun { get; }
public void Reset()
{
BlockEvent.Reset();
RunningEvent.Reset();
SyntaxDocumentIds.Clear();
DocumentIds.Clear();
ProjectIds.Clear();
InvalidateDocumentIds.Clear();
InvalidateProjectIds.Clear();
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.ProjectIds.Add(project.Id);
return Task.CompletedTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
if (bodyOpt == null)
{
this.DocumentIds.Add(document.Id);
}
return Task.CompletedTask;
}
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.SyntaxDocumentIds.Add(document.Id);
Process(document.Id, cancellationToken);
return Task.CompletedTask;
}
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
InvalidateDocumentIds.Add(documentId);
return Task.CompletedTask;
}
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken)
{
InvalidateProjectIds.Add(projectId);
return Task.CompletedTask;
}
private void Process(DocumentId _, CancellationToken cancellationToken)
{
if (BlockedRun && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
// Wait until unblocked
this.BlockEvent.Wait();
}
if (WaitForCancellation && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
cancellationToken.WaitHandle.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
}
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TestOption
|| e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption
|| e.Option == SolutionCrawlerOptions.SolutionBackgroundAnalysisScopeOption;
}
#region unused
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
#endregion
}
private class Analyzer2 : IIncrementalAnalyzer
{
public readonly List<DocumentId> DocumentIds = new List<DocumentId>();
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.DocumentIds.Add(document.Id);
return Task.CompletedTask;
}
#region unused
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false;
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask;
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask;
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask;
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask;
#endregion
}
#if false
private string GetListenerTrace(ExportProvider provider)
{
var sb = new StringBuilder();
var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener;
sb.AppendLine("workspace");
sb.AppendLine(workspaceWaiter.Trace());
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener;
sb.AppendLine("solutionCrawler");
sb.AppendLine(solutionCrawlerWaiter.Trace());
return sb.ToString();
}
internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly object gate = new object();
private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>();
private readonly StringBuilder sb = new StringBuilder();
private int counter;
public TestAsynchronousOperationListener()
{
}
public IAsyncToken BeginAsyncOperation(string name, object tag = null)
{
lock (gate)
{
return new AsyncToken(this, name);
}
}
private void Increment(string name)
{
lock (gate)
{
sb.AppendLine("i -> " + name + ":" + counter++);
}
}
private void Decrement(string name)
{
lock (gate)
{
counter--;
if (counter == 0)
{
foreach (var task in pendingTasks)
{
task.SetResult(true);
}
pendingTasks.Clear();
}
sb.AppendLine("d -> " + name + ":" + counter);
}
}
public virtual Task CreateWaitTask()
{
lock (gate)
{
var source = new TaskCompletionSource<bool>();
if (counter == 0)
{
// There is nothing to wait for, so we are immediately done
source.SetResult(true);
}
else
{
pendingTasks.Add(source);
}
return source.Task;
}
}
public bool TrackActiveTokens { get; set; }
public bool HasPendingWork
{
get
{
return counter != 0;
}
}
private class AsyncToken : IAsyncToken
{
private readonly TestAsynchronousOperationListener listener;
private readonly string name;
private bool disposed;
public AsyncToken(TestAsynchronousOperationListener listener, string name)
{
this.listener = listener;
this.name = name;
listener.Increment(name);
}
public void Dispose()
{
lock (listener.gate)
{
if (disposed)
{
throw new InvalidOperationException("Double disposing of an async token");
}
disposed = true;
listener.Decrement(this.name);
}
}
}
public string Trace()
{
return sb.ToString();
}
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler
{
[UseExportProvider]
public class WorkCoordinatorTests : TestBase
{
private const string SolutionCrawlerWorkspaceKind = "SolutionCrawler";
[Fact]
public async Task RegisterService()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
Assert.Empty(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider>());
var registrationService = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
// register and unregister workspace to the service
registrationService.Register(workspace);
registrationService.Unregister(workspace);
// make sure we wait for all waiter. the test wrongly assumed there won't be
// any pending async event which is implementation detail when creating workspace
// and changing options.
await WaitWaiterAsync(workspace.ExportProvider);
}
[Fact]
public async Task DynamicallyAddAnalyzer()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
// create solution and wait for it to settle
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
// create solution crawler and add new analyzer provider dynamically
Assert.Empty(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider>());
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var worker = new Analyzer();
var provider = new AnalyzerProvider(worker);
service.AddAnalyzerProvider(provider, Metadata.Crawler);
// wait for everything to settle
await WaitAsync(service, workspace);
service.Unregister(workspace);
// check whether everything ran as expected
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory, WorkItem(747226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747226")]
internal async Task SolutionAdded_Simple(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionId = SolutionId.CreateNewId();
var projectId = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
})
});
var expectedDocumentEvents = 1;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task SolutionAdded_Complex(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
var expectedDocumentEvents = 10;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Remove(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Clear(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.ClearSolution());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Reload(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentEvents = 10;
var expectedProjectEvents = 2;
var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution));
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(expectedProjectEvents, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Solution_Change(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.First().DocumentIds[0];
solution = solution.RemoveDocument(documentId);
var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution;
var expectedDocumentEvents = 1;
var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Add(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new List<DocumentInfo>
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2")
});
var expectedDocumentEvents = 2;
var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo));
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Remove(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var projectid = workspace.CurrentSolution.ProjectIds[0];
var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Change(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First();
var documentId = project.DocumentIds[0];
var solution = workspace.CurrentSolution.RemoveDocument(documentId);
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_AssemblyName_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.WithAssemblyName("newName");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_DefaultNamespace_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.WithDefaultNamespace("newNamespace");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_AnalyzerOptions_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
project = project.AddAdditionalDocument("a1", SourceText.From("")).Project;
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_OutputFilePath_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectOutputFilePath(project.Id, "/newPath");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_OutputRefFilePath_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectOutputRefFilePath(project.Id, "/newPath");
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_CompilationOutputInfo_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var newSolution = workspace.CurrentSolution.WithProjectCompilationOutputInfo(project.Id, new CompilationOutputInfo(assemblyPath: "/newPath"));
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Project_RunAnalyzers_Change(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
Assert.True(project.State.RunAnalyzers);
var newSolution = workspace.CurrentSolution.WithRunAnalyzers(project.Id, false);
var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, newSolution));
project = workspace.CurrentSolution.GetProject(project.Id);
Assert.False(project.State.RunAnalyzers);
var expectedDocumentEvents = 5;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
}
[Fact]
public async Task Test_NeedsReanalysisOnOptionChanged()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(Analyzer.TestOption, false))));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[Fact]
public async Task Test_BackgroundAnalysisScopeOptionChanged_ActiveFile()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
MakeFirstDocumentActive(workspace.CurrentSolution.Projects.First());
await WaitWaiterAsync(workspace.ExportProvider);
Assert.Equal(BackgroundAnalysisScope.Default, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
var newAnalysisScope = BackgroundAnalysisScope.ActiveFile;
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, newAnalysisScope))));
Assert.Equal(newAnalysisScope, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[Fact]
public async Task Test_BackgroundAnalysisScopeOptionChanged_FullSolution()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solutionInfo);
await WaitWaiterAsync(workspace.ExportProvider);
Assert.Equal(BackgroundAnalysisScope.Default, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
var newAnalysisScope = BackgroundAnalysisScope.FullSolution;
var worker = await ExecuteOperation(workspace, w => w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, newAnalysisScope))));
Assert.Equal(newAnalysisScope, SolutionCrawlerOptions.GetBackgroundAnalysisScope(workspace.Options, LanguageNames.CSharp));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
Assert.Equal(10, worker.DocumentIds.Count);
Assert.Equal(2, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects)]
[InlineData(BackgroundAnalysisScope.FullSolution)]
[Theory]
internal async Task Project_Reload(BackgroundAnalysisScope analysisScope)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentEvents = 5;
var expectedProjectEvents = 1;
var project = solution.Projects[0];
var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project));
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(expectedProjectEvents, worker.ProjectIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Add(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1");
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = await ExecuteOperation(workspace, w =>
{
w.OnDocumentAdded(info);
if (activeDocument)
{
var document = w.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
});
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 6;
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Remove(BackgroundAnalysisScope analysisScope, bool removeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (removeActiveDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(document.Id));
var expectedDocumentInvalidatedEvents = 1;
var expectedDocumentSyntaxEvents = 0;
var expectedDocumentSemanticEvents = 4;
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
Assert.Equal(expectedDocumentInvalidatedEvents, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Reload(BackgroundAnalysisScope analysisScope, bool reloadActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var info = solution.Projects[0].Documents[0];
if (reloadActiveDocument)
{
var document = workspace.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(info));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(0, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_Reanalyze(BackgroundAnalysisScope analysisScope, bool reanalyzeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var info = solution.Projects[0].Documents[0];
if (reanalyzeActiveDocument)
{
var document = workspace.CurrentSolution.GetDocument(info.Id);
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(worker.WaitForCancellation);
Assert.False(worker.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
await TouchEverything(workspace.CurrentSolution);
service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable(info.Id), highPriority: false);
await TouchEverything(workspace.CurrentSolution);
await WaitAsync(service, workspace);
service.Unregister(workspace);
var expectedReanalyzeDocumentCount = 1;
Assert.Equal(expectedReanalyzeDocumentCount, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedReanalyzeDocumentCount, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Change(BackgroundAnalysisScope analysisScope, bool changeActiveDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (changeActiveDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(document.Id, SourceText.From("//")));
var expectedDocumentEvents = 1;
Assert.Equal(expectedDocumentEvents, worker.SyntaxDocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_AdditionalFileChange(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var project = workspace.CurrentSolution.Projects.First();
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 5;
var expectedDocumentSemanticEvents = 5;
var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory]
internal async Task Document_AnalyzerConfigFileChange(BackgroundAnalysisScope analysisScope, bool firstDocumentActive)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var project = workspace.CurrentSolution.Projects.First();
if (firstDocumentActive)
{
MakeFirstDocumentActive(project);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 5;
var expectedDocumentSemanticEvents = 5;
var analyzerConfigDocFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(Temp.CreateDirectory().Path, ".editorconfig");
var analyzerConfigFile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), ".editorconfig", filePath: analyzerConfigDocFilePath);
var worker = await ExecuteOperation(workspace, w => w.OnAnalyzerConfigDocumentAdded(analyzerConfigFile));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.ChangeAnalyzerConfigDocument(analyzerConfigFile.Id, SourceText.From("//")));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
worker = await ExecuteOperation(workspace, w => w.OnAnalyzerConfigDocumentRemoved(analyzerConfigFile.Id));
Assert.Equal(expectedDocumentSyntaxEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, worker.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Cancellation(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (activeDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.True(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 5;
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
workspace.ChangeDocument(document.Id, SourceText.From("//"));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
}
token.Dispose();
workspace.ChangeDocument(document.Id, SourceText.From("// "));
await WaitAsync(service, workspace);
await expeditedWait;
service.Unregister(workspace);
Assert.Equal(expectedDocumentSyntaxEvents, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, analyzer.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_Cancellation_MultipleTimes(BackgroundAnalysisScope analysisScope, bool activeDocument)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (activeDocument)
{
MakeDocumentActive(document);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedDocumentSyntaxEvents = 1;
var expectedDocumentSemanticEvents = 5;
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.True(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
workspace.ChangeDocument(document.Id, SourceText.From("//"));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
analyzer.RunningEvent.Reset();
}
workspace.ChangeDocument(document.Id, SourceText.From("// "));
if (expectedDocumentSyntaxEvents > 0 || expectedDocumentSemanticEvents > 0)
{
analyzer.RunningEvent.Wait();
}
token.Dispose();
workspace.ChangeDocument(document.Id, SourceText.From("// "));
await WaitAsync(service, workspace);
await expeditedWait;
service.Unregister(workspace);
Assert.Equal(expectedDocumentSyntaxEvents, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentSemanticEvents, analyzer.DocumentIds.Count);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21082"), WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
public async Task Document_InvocationReasons()
{
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(analyzer.WaitForCancellation);
Assert.True(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
// first invocation will block worker
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
var openReady = new ManualResetEventSlim(initialState: false);
var closeReady = new ManualResetEventSlim(initialState: false);
workspace.DocumentOpened += (o, e) => openReady.Set();
workspace.DocumentClosed += (o, e) => closeReady.Set();
// cause several different request to queue up
workspace.ChangeDocument(id, SourceText.From("// "));
workspace.OpenDocument(id);
workspace.CloseDocument(id);
openReady.Set();
closeReady.Set();
analyzer.BlockEvent.Set();
await WaitAsync(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
[InlineData(BackgroundAnalysisScope.ActiveFile, false)]
[InlineData(BackgroundAnalysisScope.ActiveFile, true)]
[InlineData(BackgroundAnalysisScope.OpenFilesAndProjects, false)]
[InlineData(BackgroundAnalysisScope.FullSolution, false)]
[Theory, WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")]
internal async Task Document_ActiveDocumentChanged(BackgroundAnalysisScope analysisScope, bool hasActiveDocumentBefore)
{
using var workspace = WorkCoordinatorWorkspace.CreateWithAnalysisScope(analysisScope, SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
var solution = GetInitialSolutionInfo_2Projects_10Documents();
workspace.OnSolutionAdded(solution);
var documents = workspace.CurrentSolution.Projects.First().Documents.ToArray();
var firstDocument = documents[0];
var secondDocument = documents[1];
if (hasActiveDocumentBefore)
{
MakeDocumentActive(firstDocument);
}
await WaitWaiterAsync(workspace.ExportProvider);
var expectedSyntaxDocumentEvents = (analysisScope, hasActiveDocumentBefore) switch
{
(BackgroundAnalysisScope.ActiveFile, _) => 1,
(BackgroundAnalysisScope.OpenFilesAndProjects or BackgroundAnalysisScope.FullSolution, _) => 0,
_ => throw ExceptionUtilities.Unreachable,
};
var expectedDocumentEvents = (analysisScope, hasActiveDocumentBefore) switch
{
(BackgroundAnalysisScope.ActiveFile, _) => 5,
(BackgroundAnalysisScope.OpenFilesAndProjects or BackgroundAnalysisScope.FullSolution, _) => 0,
_ => throw ExceptionUtilities.Unreachable,
};
// Switch to another active source document and verify expected document analysis callbacks
var worker = await ExecuteOperation(workspace, w => MakeDocumentActive(secondDocument));
Assert.Equal(expectedSyntaxDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
// Switch from an active source document to an active non-source document and verify no document analysis callbacks
worker = await ExecuteOperation(workspace, w => ClearActiveDocument(w));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(0, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
// Switch from an active non-source document to an active source document and verify document analysis callbacks
worker = await ExecuteOperation(workspace, w => MakeDocumentActive(firstDocument));
Assert.Equal(expectedSyntaxDocumentEvents, worker.SyntaxDocumentIds.Count);
Assert.Equal(expectedDocumentEvents, worker.DocumentIds.Count);
Assert.Equal(0, worker.InvalidateDocumentIds.Count);
}
[Fact]
public async Task Document_TopLevelType_Whitespace()
{
var code = @"class C { $$ }";
var textToInsert = " ";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_Character()
{
var code = @"class C { $$ }";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_NewLine()
{
var code = @"class C { $$ }";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelType_NewLine2()
{
var code = @"class C { $$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_EmptyFile()
{
var code = @"$$";
var textToInsert = "class";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel1()
{
var code = @"class C
{
public void Test($$";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel2()
{
var code = @"class C
{
public void Test(int $$";
var textToInsert = " ";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevel3()
{
var code = @"class C
{
public void Test(int i,$$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_InteriorNode1()
{
var code = @"class C
{
public void Test()
{$$";
var textToInsert = "\r\n";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode2()
{
var code = @"class C
{
public void Test()
{
$$
}";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Field()
{
var code = @"class C
{
int i = $$
}";
var textToInsert = "1";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Field1()
{
var code = @"class C
{
int i = 1 + $$
}";
var textToInsert = "1";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_InteriorNode_Accessor()
{
var code = @"class C
{
public int A
{
get
{
$$
}
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public async Task Document_TopLevelWhitespace()
{
var code = @"class C
{
/// $$
public int A()
{
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_TopLevelWhitespace2()
{
var code = @"/// $$
class C
{
public int A()
{
}
}";
var textToInsert = "return";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public async Task Document_InteriorNode_Malformed()
{
var code = @"class C
{
public void Test()
{
$$";
var textToInsert = "int";
await InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")]
public async Task SemanticChange_Propagation_Transitive()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, false)));
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
}
[Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")]
public async Task SemanticChange_Propagation_Direct()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProviderNoWaitNoBlock));
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, true)));
workspace.OnSolutionAdded(solution);
await WaitWaiterAsync(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(3, worker.DocumentIds.Count);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/23657")]
public async Task ProgressReporterTest()
{
var solution = GetInitialSolutionInfoWithP2P();
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind);
await WaitWaiterAsync(workspace.ExportProvider);
var service = workspace.Services.GetService<ISolutionCrawlerService>();
var reporter = service.GetProgressReporter(workspace);
Assert.False(reporter.InProgress);
// set up events
var started = false;
var stopped = false;
reporter.ProgressChanged += (o, s) =>
{
if (s.Status == ProgressStatus.Started)
{
started = true;
}
else if (s.Status == ProgressStatus.Stopped)
{
stopped = true;
}
};
var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();
registrationService.Register(workspace);
// first mutation
workspace.OnSolutionAdded(solution);
await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
// reset
started = false;
stopped = false;
// second mutation
workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6"));
await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
registrationService.Unregister(workspace);
}
[Fact]
[WorkItem(26244, "https://github.com/dotnet/roslyn/issues/26244")]
public async Task FileFromSameProjectTogetherTest()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: GetDocuments(projectId1, count: 5)),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: GetDocuments(projectId2, count: 5)),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: GetDocuments(projectId3, count: 5))
});
using var workspace = new WorkCoordinatorWorkspace(SolutionCrawlerWorkspaceKind, incrementalAnalyzer: typeof(AnalyzerProvider2));
await WaitWaiterAsync(workspace.ExportProvider);
// add analyzer
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer2>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
// enable solution crawler
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
await WaitWaiterAsync(workspace.ExportProvider);
var listenerProvider = GetListenerProvider(workspace.ExportProvider);
// start an operation that allows an expedited wait to cover the remainder of the delayed operations in the test
var token = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler).BeginAsyncOperation("Test operation");
var expeditedWait = listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync();
// we want to test order items processed by solution crawler.
// but since everything async, lazy and cancellable, order is not 100% deterministic. an item might
// start to be processed, and get cancelled due to newly enqueued item requiring current work to be re-processed
// (ex, new file being added).
// this behavior is expected in real world, but it makes testing hard. so to make ordering deterministic
// here we first block solution crawler from processing any item using global operation.
// and then make sure all delayed work item enqueue to be done through waiters. work item enqueue is async
// and delayed since one of responsibility of solution cralwer is aggregating workspace events to fewer
// work items.
// once we are sure everything is stablized, we let solution crawler to process by releasing global operation.
// what this test is interested in is the order solution crawler process the pending works. so this should
// let the test not care about cancellation or work not enqueued yet.
// block solution cralwer from processing.
var globalOperation = workspace.Services.GetService<IGlobalOperationNotificationService>();
using (var operation = globalOperation.Start("Block SolutionCrawler"))
{
// make sure global operaiton is actually started
// otherwise, solution crawler might processed event we are later waiting for
var operationWaiter = GetListenerProvider(workspace.ExportProvider).GetWaiter(FeatureAttribute.GlobalOperation);
await operationWaiter.ExpeditedWaitAsync();
// mutate solution
workspace.OnSolutionAdded(solution);
// wait for workspace events to be all processed
var workspaceWaiter = GetListenerProvider(workspace.ExportProvider).GetWaiter(FeatureAttribute.Workspace);
await workspaceWaiter.ExpeditedWaitAsync();
// now wait for semantic processor to finish
var crawlerListener = (AsynchronousOperationListener)GetListenerProvider(workspace.ExportProvider).GetListener(FeatureAttribute.SolutionCrawler);
// first, wait for first work to be queued.
//
// since asyncToken doesn't distinguish whether (1) certain event is happened but all processed or (2) it never happened yet,
// to check (1), we must wait for first item, and then wait for all items to be processed.
await crawlerListener.WaitUntilConditionIsMetAsync(
pendingTokens => pendingTokens.Any(token => token.Tag == (object)SolutionCrawlerRegistrationService.EnqueueItem));
// and then wait them to be processed
await crawlerListener.WaitUntilConditionIsMetAsync(pendingTokens => pendingTokens.Where(token => token.Tag == workspace).IsEmpty());
// let analyzer to process
operation.Done();
}
token.Dispose();
// wait analyzers to finish process
await WaitAsync(service, workspace);
await expeditedWait;
Assert.Equal(1, worker.DocumentIds.Take(5).Select(d => d.ProjectId).Distinct().Count());
Assert.Equal(1, worker.DocumentIds.Skip(5).Take(5).Select(d => d.ProjectId).Distinct().Count());
Assert.Equal(1, worker.DocumentIds.Skip(10).Take(5).Select(d => d.ProjectId).Distinct().Count());
service.Unregister(workspace);
}
private static async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
{
using var workspace = TestWorkspace.Create(
language,
compilationOptions: null,
parseOptions: null,
new[] { code },
composition: EditorTestCompositions.EditorFeatures.AddExcludedPartTypes(typeof(IIncrementalAnalyzerProvider)).AddParts(typeof(AnalyzerProviderNoWaitNoBlock)),
workspaceKind: SolutionCrawlerWorkspaceKind);
var testDocument = workspace.Documents.First();
var textBuffer = testDocument.GetTextBuffer();
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var analyzer = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(analyzer.WaitForCancellation);
Assert.False(analyzer.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
service.Register(workspace);
var insertPosition = testDocument.CursorPosition;
using (var edit = textBuffer.CreateEdit())
{
edit.Insert(insertPosition.Value, text);
edit.Apply();
}
await WaitAsync(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
}
private static async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation)
{
var lazyWorker = Assert.Single(workspace.ExportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>());
Assert.Equal(Metadata.Crawler, lazyWorker.Metadata);
var worker = Assert.IsType<Analyzer>(Assert.IsAssignableFrom<AnalyzerProvider>(lazyWorker.Value).Analyzer);
Assert.False(worker.WaitForCancellation);
Assert.False(worker.BlockedRun);
var service = Assert.IsType<SolutionCrawlerRegistrationService>(workspace.Services.GetService<ISolutionCrawlerRegistrationService>());
worker.Reset();
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
await TouchEverything(workspace.CurrentSolution);
operation(workspace);
await TouchEverything(workspace.CurrentSolution);
await WaitAsync(service, workspace);
service.Unregister(workspace);
return worker;
}
private static async Task TouchEverything(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
await document.GetTextAsync();
await document.GetSyntaxRootAsync();
await document.GetSemanticModelAsync();
}
}
}
private static async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace)
{
await WaitWaiterAsync(workspace.ExportProvider);
service.GetTestAccessor().WaitUntilCompletion(workspace);
}
private static async Task WaitWaiterAsync(ExportProvider provider)
{
var workspaceWaiter = GetListenerProvider(provider).GetWaiter(FeatureAttribute.Workspace);
await workspaceWaiter.ExpeditedWaitAsync();
var solutionCrawlerWaiter = GetListenerProvider(provider).GetWaiter(FeatureAttribute.SolutionCrawler);
await solutionCrawlerWaiter.ExpeditedWaitAsync();
}
private static SolutionInfo GetInitialSolutionInfoWithP2P()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var projectId4 = ProjectId.CreateNewId();
var projectId5 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
projectReferences: new[] { new ProjectReference(projectId1) }),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
projectReferences: new[] { new ProjectReference(projectId2) }),
ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
projectReferences: new[] { new ProjectReference(projectId4) }),
});
return solution;
}
private static SolutionInfo GetInitialSolutionInfo_2Projects_10Documents()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: GetDocuments(projectId1, count: 5)),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: GetDocuments(projectId2, count: 5))
});
}
private static IEnumerable<DocumentInfo> GetDocuments(ProjectId projectId, int count)
{
for (var i = 0; i < count; i++)
{
yield return DocumentInfo.Create(DocumentId.CreateNewId(projectId), $"D{i + 1}");
}
}
private static AsynchronousOperationListenerProvider GetListenerProvider(ExportProvider provider)
=> provider.GetExportedValue<AsynchronousOperationListenerProvider>();
private static void MakeFirstDocumentActive(Project project)
=> MakeDocumentActive(project.Documents.First());
private static void MakeDocumentActive(Document document)
{
var documentTrackingService = (TestDocumentTrackingService)document.Project.Solution.Workspace.Services.GetRequiredService<IDocumentTrackingService>();
documentTrackingService.SetActiveDocument(document.Id);
}
private static void ClearActiveDocument(Workspace workspace)
{
var documentTrackingService = (TestDocumentTrackingService)workspace.Services.GetService<IDocumentTrackingService>();
documentTrackingService.SetActiveDocument(null);
}
private class WorkCoordinatorWorkspace : TestWorkspace
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestDocumentTrackingService)).AddExcludedPartTypes(typeof(IIncrementalAnalyzerProvider));
private readonly IAsynchronousOperationWaiter _workspaceWaiter;
private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter;
public WorkCoordinatorWorkspace(string workspaceKind = null, bool disablePartialSolutions = true, Type incrementalAnalyzer = null)
: base(composition: incrementalAnalyzer is null ? s_composition : s_composition.AddParts(incrementalAnalyzer), workspaceKind: workspaceKind, disablePartialSolutions: disablePartialSolutions)
{
_workspaceWaiter = GetListenerProvider(ExportProvider).GetWaiter(FeatureAttribute.Workspace);
_solutionCrawlerWaiter = GetListenerProvider(ExportProvider).GetWaiter(FeatureAttribute.SolutionCrawler);
Assert.False(_workspaceWaiter.HasPendingWork);
Assert.False(_solutionCrawlerWaiter.HasPendingWork);
}
public static WorkCoordinatorWorkspace CreateWithAnalysisScope(BackgroundAnalysisScope analysisScope, string workspaceKind = null, bool disablePartialSolutions = true, Type incrementalAnalyzer = null)
{
var workspace = new WorkCoordinatorWorkspace(workspaceKind, disablePartialSolutions, incrementalAnalyzer);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, analysisScope)));
return workspace;
}
protected override void Dispose(bool finalize)
{
base.Dispose(finalize);
Assert.False(_workspaceWaiter.HasPendingWork);
Assert.False(_solutionCrawlerWaiter.HasPendingWork);
}
}
private class AnalyzerProvider : IIncrementalAnalyzerProvider
{
public readonly IIncrementalAnalyzer Analyzer;
public AnalyzerProvider(IIncrementalAnalyzer analyzer)
=> Analyzer = analyzer;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
=> Analyzer;
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderNoWaitNoBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderNoWaitNoBlock()
: base(new Analyzer())
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderWaitNoBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderWaitNoBlock()
: base(new Analyzer(waitForCancellation: true))
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProviderNoWaitBlock : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProviderNoWaitBlock()
: base(new Analyzer(blockedRun: true))
{
}
}
[ExportIncrementalAnalyzerProvider(name: "TestAnalyzer", workspaceKinds: new[] { SolutionCrawlerWorkspaceKind })]
[Shared]
[PartNotDiscoverable]
private class AnalyzerProvider2 : AnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerProvider2()
: base(new Analyzer2())
{
}
}
internal static class Metadata
{
public static readonly IncrementalAnalyzerProviderMetadata Crawler = new IncrementalAnalyzerProviderMetadata(new Dictionary<string, object> { { "WorkspaceKinds", new[] { SolutionCrawlerWorkspaceKind } }, { "HighPriorityForActiveFile", false }, { "Name", "TestAnalyzer" } });
}
private class Analyzer : IIncrementalAnalyzer
{
public static readonly Option<bool> TestOption = new Option<bool>("TestOptions", "TestOption", defaultValue: true);
public readonly ManualResetEventSlim BlockEvent;
public readonly ManualResetEventSlim RunningEvent;
public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>();
public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>();
public Analyzer(bool waitForCancellation = false, bool blockedRun = false)
{
WaitForCancellation = waitForCancellation;
BlockedRun = blockedRun;
this.BlockEvent = new ManualResetEventSlim(initialState: false);
this.RunningEvent = new ManualResetEventSlim(initialState: false);
}
public bool WaitForCancellation { get; }
public bool BlockedRun { get; }
public void Reset()
{
BlockEvent.Reset();
RunningEvent.Reset();
SyntaxDocumentIds.Clear();
DocumentIds.Clear();
ProjectIds.Clear();
InvalidateDocumentIds.Clear();
InvalidateProjectIds.Clear();
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.ProjectIds.Add(project.Id);
return Task.CompletedTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
if (bodyOpt == null)
{
this.DocumentIds.Add(document.Id);
}
return Task.CompletedTask;
}
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.SyntaxDocumentIds.Add(document.Id);
Process(document.Id, cancellationToken);
return Task.CompletedTask;
}
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
InvalidateDocumentIds.Add(documentId);
return Task.CompletedTask;
}
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken)
{
InvalidateProjectIds.Add(projectId);
return Task.CompletedTask;
}
private void Process(DocumentId _, CancellationToken cancellationToken)
{
if (BlockedRun && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
// Wait until unblocked
this.BlockEvent.Wait();
}
if (WaitForCancellation && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
cancellationToken.WaitHandle.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
}
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TestOption
|| e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption
|| e.Option == SolutionCrawlerOptions.SolutionBackgroundAnalysisScopeOption;
}
#region unused
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
#endregion
}
private class Analyzer2 : IIncrementalAnalyzer
{
public readonly List<DocumentId> DocumentIds = new List<DocumentId>();
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
this.DocumentIds.Add(document.Id);
return Task.CompletedTask;
}
#region unused
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false;
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask;
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask;
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask;
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask;
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask;
#endregion
}
#if false
private string GetListenerTrace(ExportProvider provider)
{
var sb = new StringBuilder();
var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener;
sb.AppendLine("workspace");
sb.AppendLine(workspaceWaiter.Trace());
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener;
sb.AppendLine("solutionCrawler");
sb.AppendLine(solutionCrawlerWaiter.Trace());
return sb.ToString();
}
internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly object gate = new object();
private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>();
private readonly StringBuilder sb = new StringBuilder();
private int counter;
public TestAsynchronousOperationListener()
{
}
public IAsyncToken BeginAsyncOperation(string name, object tag = null)
{
lock (gate)
{
return new AsyncToken(this, name);
}
}
private void Increment(string name)
{
lock (gate)
{
sb.AppendLine("i -> " + name + ":" + counter++);
}
}
private void Decrement(string name)
{
lock (gate)
{
counter--;
if (counter == 0)
{
foreach (var task in pendingTasks)
{
task.SetResult(true);
}
pendingTasks.Clear();
}
sb.AppendLine("d -> " + name + ":" + counter);
}
}
public virtual Task CreateWaitTask()
{
lock (gate)
{
var source = new TaskCompletionSource<bool>();
if (counter == 0)
{
// There is nothing to wait for, so we are immediately done
source.SetResult(true);
}
else
{
pendingTasks.Add(source);
}
return source.Task;
}
}
public bool TrackActiveTokens { get; set; }
public bool HasPendingWork
{
get
{
return counter != 0;
}
}
private class AsyncToken : IAsyncToken
{
private readonly TestAsynchronousOperationListener listener;
private readonly string name;
private bool disposed;
public AsyncToken(TestAsynchronousOperationListener listener, string name)
{
this.listener = listener;
this.name = name;
listener.Increment(name);
}
public void Dispose()
{
lock (listener.gate)
{
if (disposed)
{
throw new InvalidOperationException("Double disposing of an async token");
}
disposed = true;
listener.Decrement(this.name);
}
}
}
public string Trace()
{
return sb.ToString();
}
}
#endif
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.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.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class OperatorOverloadSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(BinaryExpressionSyntax),
GetType(UnaryExpressionSyntax))
Public Overrides Sub AddClassifications(
workspace As Workspace,
syntax As SyntaxNode,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then
If TypeOf syntax Is BinaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
End If
End If
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class OperatorOverloadSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(BinaryExpressionSyntax),
GetType(UnaryExpressionSyntax))
Public Overrides Sub AddClassifications(
workspace As Workspace,
syntax As SyntaxNode,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then
If TypeOf syntax Is BinaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
End If
End If
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/EditorFeatures/Core/Implementation/TodoComment/TodoItemsUpdatedArgs.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.TodoComments;
namespace Microsoft.CodeAnalysis.Editor
{
internal sealed class TodoItemsUpdatedArgs : UpdatedEventArgs
{
/// <summary>
/// Solution this task items are associated with
/// </summary>
public Solution Solution { get; }
/// <summary>
/// The task items associated with the ID.
/// </summary>
public ImmutableArray<TodoCommentData> TodoItems { get; }
public TodoItemsUpdatedArgs(
object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<TodoCommentData> todoItems)
: base(id, workspace, projectId, documentId)
{
Solution = solution;
TodoItems = todoItems;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.TodoComments;
namespace Microsoft.CodeAnalysis.Editor
{
internal sealed class TodoItemsUpdatedArgs : UpdatedEventArgs
{
/// <summary>
/// Solution this task items are associated with
/// </summary>
public Solution Solution { get; }
/// <summary>
/// The task items associated with the ID.
/// </summary>
public ImmutableArray<TodoCommentData> TodoItems { get; }
public TodoItemsUpdatedArgs(
object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<TodoCommentData> todoItems)
: base(id, workspace, projectId, documentId)
{
Solution = solution;
TodoItems = todoItems;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/PEWriter/RootModuleType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
/// <summary>
/// Special type <Module>
/// </summary>
internal class RootModuleType : INamespaceTypeDefinition
{
private IReadOnlyList<IMethodDefinition>? _methods;
public void SetStaticConstructorBody(ImmutableArray<byte> il)
{
Debug.Assert(_methods is null);
_methods = SpecializedCollections.SingletonReadOnlyList(
new RootModuleStaticConstructor(containingTypeDefinition: this, il));
}
public IEnumerable<IMethodDefinition> GetMethods(EmitContext context)
{
return _methods ??= SpecializedCollections.EmptyReadOnlyList<IMethodDefinition>();
}
public TypeDefinitionHandle TypeDef
{
get { return default(TypeDefinitionHandle); }
}
public ITypeDefinition ResolvedType
{
get { return this; }
}
public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<ICustomAttribute>();
}
public bool MangleName
{
get { return false; }
}
public string Name
{
get { return "<Module>"; }
}
public ushort Alignment
{
get { return 0; }
}
public ITypeReference? GetBaseClass(EmitContext context)
{
return null;
}
public IEnumerable<IEventDefinition> GetEvents(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IEventDefinition>();
}
public IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<MethodImplementation>();
}
public IEnumerable<IFieldDefinition> GetFields(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IFieldDefinition>();
}
public bool HasDeclarativeSecurity
{
get { return false; }
}
public IEnumerable<Cci.TypeReferenceWithAttributes> Interfaces(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.TypeReferenceWithAttributes>();
}
public bool IsAbstract
{
get { return false; }
}
public bool IsBeforeFieldInit
{
get { return false; }
}
public bool IsComObject
{
get { return false; }
}
public bool IsGeneric
{
get { return false; }
}
public bool IsInterface
{
get { return false; }
}
public bool IsDelegate
{
get { return false; }
}
public bool IsRuntimeSpecial
{
get { return false; }
}
public bool IsSerializable
{
get { return false; }
}
public bool IsSpecialName
{
get { return false; }
}
public bool IsWindowsRuntimeImport
{
get { return false; }
}
public bool IsSealed
{
get { return false; }
}
public LayoutKind Layout
{
get { return LayoutKind.Auto; }
}
public IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<INestedTypeDefinition>();
}
public IEnumerable<IPropertyDefinition> GetProperties(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IPropertyDefinition>();
}
public uint SizeOf
{
get { return 0; }
}
public CharSet StringFormat
{
get { return CharSet.Ansi; }
}
public bool IsPublic
{
get { return false; }
}
public bool IsNested
{
get { return false; }
}
IEnumerable<IGenericTypeParameter> ITypeDefinition.GenericParameters
{
get { throw ExceptionUtilities.Unreachable; }
}
ushort ITypeDefinition.GenericParameterCount
{
get
{
return 0;
}
}
IEnumerable<SecurityAttribute> ITypeDefinition.SecurityAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
void IReference.Dispatch(MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
bool ITypeReference.IsEnum
{
get { throw ExceptionUtilities.Unreachable; }
}
bool ITypeReference.IsValueType
{
get { throw ExceptionUtilities.Unreachable; }
}
ITypeDefinition ITypeReference.GetResolvedType(EmitContext context)
{
return this;
}
PrimitiveTypeCode ITypeReference.TypeCode
{
get { throw ExceptionUtilities.Unreachable; }
}
ushort INamedTypeReference.GenericParameterCount
{
get { throw ExceptionUtilities.Unreachable; }
}
IUnitReference INamespaceTypeReference.GetUnit(EmitContext context)
{
throw ExceptionUtilities.Unreachable;
}
string INamespaceTypeReference.NamespaceName
{
get
{
return string.Empty;
}
}
IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return this;
}
INamespaceTypeReference ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
INestedTypeReference? ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context)
{
return this;
}
IDefinition IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object? obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
/// <summary>
/// Special type <Module>
/// </summary>
internal class RootModuleType : INamespaceTypeDefinition
{
private IReadOnlyList<IMethodDefinition>? _methods;
public void SetStaticConstructorBody(ImmutableArray<byte> il)
{
Debug.Assert(_methods is null);
_methods = SpecializedCollections.SingletonReadOnlyList(
new RootModuleStaticConstructor(containingTypeDefinition: this, il));
}
public IEnumerable<IMethodDefinition> GetMethods(EmitContext context)
{
return _methods ??= SpecializedCollections.EmptyReadOnlyList<IMethodDefinition>();
}
public TypeDefinitionHandle TypeDef
{
get { return default(TypeDefinitionHandle); }
}
public ITypeDefinition ResolvedType
{
get { return this; }
}
public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<ICustomAttribute>();
}
public bool MangleName
{
get { return false; }
}
public string Name
{
get { return "<Module>"; }
}
public ushort Alignment
{
get { return 0; }
}
public ITypeReference? GetBaseClass(EmitContext context)
{
return null;
}
public IEnumerable<IEventDefinition> GetEvents(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IEventDefinition>();
}
public IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<MethodImplementation>();
}
public IEnumerable<IFieldDefinition> GetFields(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IFieldDefinition>();
}
public bool HasDeclarativeSecurity
{
get { return false; }
}
public IEnumerable<Cci.TypeReferenceWithAttributes> Interfaces(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.TypeReferenceWithAttributes>();
}
public bool IsAbstract
{
get { return false; }
}
public bool IsBeforeFieldInit
{
get { return false; }
}
public bool IsComObject
{
get { return false; }
}
public bool IsGeneric
{
get { return false; }
}
public bool IsInterface
{
get { return false; }
}
public bool IsDelegate
{
get { return false; }
}
public bool IsRuntimeSpecial
{
get { return false; }
}
public bool IsSerializable
{
get { return false; }
}
public bool IsSpecialName
{
get { return false; }
}
public bool IsWindowsRuntimeImport
{
get { return false; }
}
public bool IsSealed
{
get { return false; }
}
public LayoutKind Layout
{
get { return LayoutKind.Auto; }
}
public IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<INestedTypeDefinition>();
}
public IEnumerable<IPropertyDefinition> GetProperties(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<IPropertyDefinition>();
}
public uint SizeOf
{
get { return 0; }
}
public CharSet StringFormat
{
get { return CharSet.Ansi; }
}
public bool IsPublic
{
get { return false; }
}
public bool IsNested
{
get { return false; }
}
IEnumerable<IGenericTypeParameter> ITypeDefinition.GenericParameters
{
get { throw ExceptionUtilities.Unreachable; }
}
ushort ITypeDefinition.GenericParameterCount
{
get
{
return 0;
}
}
IEnumerable<SecurityAttribute> ITypeDefinition.SecurityAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
void IReference.Dispatch(MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
bool ITypeReference.IsEnum
{
get { throw ExceptionUtilities.Unreachable; }
}
bool ITypeReference.IsValueType
{
get { throw ExceptionUtilities.Unreachable; }
}
ITypeDefinition ITypeReference.GetResolvedType(EmitContext context)
{
return this;
}
PrimitiveTypeCode ITypeReference.TypeCode
{
get { throw ExceptionUtilities.Unreachable; }
}
ushort INamedTypeReference.GenericParameterCount
{
get { throw ExceptionUtilities.Unreachable; }
}
IUnitReference INamespaceTypeReference.GetUnit(EmitContext context)
{
throw ExceptionUtilities.Unreachable;
}
string INamespaceTypeReference.NamespaceName
{
get
{
return string.Empty;
}
}
IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return this;
}
INamespaceTypeReference ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
INestedTypeReference? ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context)
{
return this;
}
IDefinition IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object? obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Binding.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// For the given set of AssemblyData objects, do the following:
/// 1) Resolve references from each assembly against other assemblies in the set.
/// 2) Choose suitable AssemblySymbol instance for each AssemblyData object.
///
/// The first element (index==0) of the assemblies array represents the assembly being built.
/// One can think about the rest of the items in assemblies array as assembly references given to the compiler to
/// build executable for the assembly being built.
/// </summary>
/// <param name="compilation">Compilation.</param>
/// <param name="explicitAssemblies">
/// An array of <see cref="AssemblyData"/> objects describing assemblies, for which this method should
/// resolve references and find suitable AssemblySymbols. The first slot contains the assembly being built.
/// </param>
/// <param name="explicitModules">
/// An array of <see cref="PEModule"/> objects describing standalone modules referenced by the compilation.
/// </param>
/// <param name="explicitReferences">
/// An array of references passed to the compilation and resolved from #r directives.
/// May contain references that were skipped during resolution (they don't have a corresponding explicit assembly).
/// </param>
/// <param name="explicitReferenceMap">
/// Maps index to <paramref name="explicitReferences"/> to an index of a resolved assembly or module in <paramref name="explicitAssemblies"/> or modules.
/// </param>
/// <param name="resolverOpt">
/// Reference resolver used to look up missing assemblies.
/// </param>
/// <param name="supersedeLowerVersions">
/// Hide lower versions of dependencies that have multiple versions behind an alias.
/// </param>
/// <param name="assemblyReferencesBySimpleName">
/// Used to filter out assemblies that have the same strong or weak identity.
/// Maps simple name to a list of identities. The highest version of each name is the first.
/// </param>
/// <param name="importOptions">
/// Import options applied to implicitly resolved references.
/// </param>
/// <param name="allAssemblies">
/// Updated array <paramref name="explicitAssemblies"/> with resolved implicitly referenced assemblies appended.
/// </param>
/// <param name="implicitlyResolvedReferences">
/// Implicitly resolved references.
/// </param>
/// <param name="implicitlyResolvedReferenceMap">
/// Maps indices of implicitly resolved references to the corresponding indices of resolved assemblies in <paramref name="allAssemblies"/> (explicit + implicit).
/// </param>
/// <param name="implicitReferenceResolutions">
/// Map of implicit reference resolutions performed in the preceding script compilation.
/// Output contains additional implicit resolutions performed during binding of this script compilation references.
/// </param>
/// <param name="resolutionDiagnostics">
/// Any diagnostics reported while resolving missing assemblies.
/// </param>
/// <param name="hasCircularReference">
/// True if the assembly being compiled is indirectly referenced through some of its own references.
/// </param>
/// <param name="corLibraryIndex">
/// The definition index of the COR library.
/// </param>
/// <return>
/// An array of <see cref="BoundInputAssembly"/> structures describing the result. It has the same amount of items as
/// the input assemblies array, <see cref="BoundInputAssembly"/> for each input AssemblyData object resides
/// at the same position.
///
/// Each <see cref="BoundInputAssembly"/> contains the following data:
///
/// - Suitable AssemblySymbol instance for the corresponding assembly,
/// null reference if none is available/found. Always null for the first element, which corresponds to the assembly being built.
///
/// - Result of resolving assembly references of the corresponding assembly
/// against provided set of assembly definitions. Essentially, this is an array returned by
/// <see cref="AssemblyData.BindAssemblyReferences(ImmutableArray{AssemblyData}, AssemblyIdentityComparer)"/> method.
/// </return>
protected BoundInputAssembly[] Bind(
TCompilation compilation,
ImmutableArray<AssemblyData> explicitAssemblies,
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
MetadataReferenceResolver? resolverOpt,
MetadataImportOptions importOptions,
bool supersedeLowerVersions,
[In, Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<AssemblyData> allAssemblies,
out ImmutableArray<MetadataReference> implicitlyResolvedReferences,
out ImmutableArray<ResolvedReference> implicitlyResolvedReferenceMap,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
[In, Out] DiagnosticBag resolutionDiagnostics,
out bool hasCircularReference,
out int corLibraryIndex)
{
Debug.Assert(explicitAssemblies[0] is AssemblyDataForAssemblyBeingBuilt);
Debug.Assert(explicitReferences.Length == explicitReferenceMap.Length);
var referenceBindings = ArrayBuilder<AssemblyReferenceBinding[]>.GetInstance();
try
{
// Based on assembly identity, for each assembly,
// bind its references against the other assemblies we have.
for (int i = 0; i < explicitAssemblies.Length; i++)
{
referenceBindings.Add(explicitAssemblies[i].BindAssemblyReferences(explicitAssemblies, IdentityComparer));
}
if (resolverOpt?.ResolveMissingAssemblies == true)
{
ResolveAndBindMissingAssemblies(
compilation,
explicitAssemblies,
explicitModules,
explicitReferences,
explicitReferenceMap,
resolverOpt,
importOptions,
supersedeLowerVersions,
referenceBindings,
assemblyReferencesBySimpleName,
out allAssemblies,
out implicitlyResolvedReferences,
out implicitlyResolvedReferenceMap,
ref implicitReferenceResolutions,
resolutionDiagnostics);
}
else
{
allAssemblies = explicitAssemblies;
implicitlyResolvedReferences = ImmutableArray<MetadataReference>.Empty;
implicitlyResolvedReferenceMap = ImmutableArray<ResolvedReference>.Empty;
}
// implicitly resolved missing assemblies were added to both referenceBindings and assemblies:
Debug.Assert(referenceBindings.Count == allAssemblies.Length);
hasCircularReference = CheckCircularReference(referenceBindings);
corLibraryIndex = IndexOfCorLibrary(explicitAssemblies, assemblyReferencesBySimpleName, supersedeLowerVersions);
// For each assembly, locate AssemblySymbol with similar reference resolution
// What does similar mean?
// Similar means:
// 1) The same references are resolved against the assemblies that we are given
// (or were found during implicit assembly resolution).
// 2) The same assembly is used as the COR library.
var boundInputs = new BoundInputAssembly[referenceBindings.Count];
for (int i = 0; i < referenceBindings.Count; i++)
{
boundInputs[i].ReferenceBinding = referenceBindings[i];
}
var candidateInputAssemblySymbols = new TAssemblySymbol[allAssemblies.Length];
// If any assembly from assemblies array refers back to assemblyBeingBuilt,
// we know that we cannot reuse symbols for any assemblies containing NoPia
// local types. Because we cannot reuse symbols for assembly referring back
// to assemblyBeingBuilt.
if (!hasCircularReference)
{
// Deal with assemblies containing NoPia local types.
if (ReuseAssemblySymbolsWithNoPiaLocalTypes(boundInputs, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex))
{
return boundInputs;
}
}
// NoPia shortcut either didn't apply or failed, go through general process
// of matching candidates.
ReuseAssemblySymbols(boundInputs, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex);
return boundInputs;
}
finally
{
referenceBindings.Free();
}
}
private void ResolveAndBindMissingAssemblies(
TCompilation compilation,
ImmutableArray<AssemblyData> explicitAssemblies,
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
MetadataReferenceResolver resolver,
MetadataImportOptions importOptions,
bool supersedeLowerVersions,
[In, Out] ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings,
[In, Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<AssemblyData> allAssemblies,
out ImmutableArray<MetadataReference> metadataReferences,
out ImmutableArray<ResolvedReference> resolvedReferences,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
DiagnosticBag resolutionDiagnostics)
{
Debug.Assert(explicitAssemblies[0] is AssemblyDataForAssemblyBeingBuilt);
Debug.Assert(referenceBindings.Count == explicitAssemblies.Length);
Debug.Assert(explicitReferences.Length == explicitReferenceMap.Length);
// -1 for assembly being built:
int totalReferencedAssemblyCount = explicitAssemblies.Length - 1;
var implicitAssemblies = ArrayBuilder<AssemblyData>.GetInstance();
// assembly identities whose resolution failed for all attempted requesting references:
var resolutionFailures = PooledHashSet<AssemblyIdentity>.GetInstance();
var metadataReferencesBuilder = ArrayBuilder<MetadataReference>.GetInstance();
Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null;
// metadata references and corresponding bindings of their references, used to calculate a fixed point:
var referenceBindingsToProcess = ArrayBuilder<(MetadataReference, ArraySegment<AssemblyReferenceBinding>)>.GetInstance();
// collect all missing identities, resolve the assemblies and bind their references against explicit definitions:
GetInitialReferenceBindingsToProcess(explicitModules, explicitReferences, explicitReferenceMap, referenceBindings, totalReferencedAssemblyCount, referenceBindingsToProcess);
// NB: includes the assembly being built:
int explicitAssemblyCount = explicitAssemblies.Length;
try
{
while (referenceBindingsToProcess.Count > 0)
{
var (requestingReference, bindings) = referenceBindingsToProcess.Pop();
foreach (var binding in bindings)
{
// only attempt to resolve unbound references (regardless of version difference of the bound ones)
if (binding.IsBound)
{
continue;
}
Debug.Assert(binding.ReferenceIdentity is object);
if (!TryResolveMissingReference(
requestingReference,
binding.ReferenceIdentity,
ref implicitReferenceResolutions,
resolver,
resolutionDiagnostics,
out AssemblyIdentity? resolvedAssemblyIdentity,
out AssemblyMetadata? resolvedAssemblyMetadata,
out PortableExecutableReference? resolvedReference))
{
// Note the failure, but do not commit it to implicitReferenceResolutions until we are done with resolving all missing references.
resolutionFailures.Add(binding.ReferenceIdentity);
continue;
}
// One attempt for resolution succeeded. The attempt is cached in implicitReferenceResolutions, so further attempts won't fail and add it back.
// Since the failures tracked in resolutionFailures do not affect binding there is no need to revert any decisions made so far.
resolutionFailures.Remove(binding.ReferenceIdentity);
// The resolver may return different version than we asked for, so it may happen that
// it returns the same identity for two different input identities (e.g. if a higher version
// of an assembly is available than what the assemblies reference: "A, v1" -> "A, v3" and "A, v2" -> "A, v3").
// If such case occurs merge the properties (aliases) of the resulting references in the same way we do
// during initial explicit references resolution.
// -1 for assembly being built:
int index = explicitAssemblyCount - 1 + metadataReferencesBuilder.Count;
var existingReference = TryAddAssembly(resolvedAssemblyIdentity, resolvedReference, index, resolutionDiagnostics, Location.None, assemblyReferencesBySimpleName, supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, resolvedReference, resolutionDiagnostics, ref lazyAliasMap);
continue;
}
metadataReferencesBuilder.Add(resolvedReference);
var data = CreateAssemblyDataForResolvedMissingAssembly(resolvedAssemblyMetadata, resolvedReference, importOptions);
implicitAssemblies.Add(data);
var referenceBinding = data.BindAssemblyReferences(explicitAssemblies, IdentityComparer);
referenceBindings.Add(referenceBinding);
referenceBindingsToProcess.Push((resolvedReference, new ArraySegment<AssemblyReferenceBinding>(referenceBinding)));
}
}
// record failures for resolution in subsequent submissions:
foreach (var assemblyIdentity in resolutionFailures)
{
implicitReferenceResolutions = implicitReferenceResolutions.Add(assemblyIdentity, null);
}
if (implicitAssemblies.Count == 0)
{
Debug.Assert(lazyAliasMap == null);
resolvedReferences = ImmutableArray<ResolvedReference>.Empty;
metadataReferences = ImmutableArray<MetadataReference>.Empty;
allAssemblies = explicitAssemblies;
return;
}
// Rebind assembly references that were initially missing. All bindings established above
// are against explicitly specified references.
allAssemblies = explicitAssemblies.AddRange(implicitAssemblies);
for (int bindingsIndex = 0; bindingsIndex < referenceBindings.Count; bindingsIndex++)
{
var referenceBinding = referenceBindings[bindingsIndex];
for (int i = 0; i < referenceBinding.Length; i++)
{
var binding = referenceBinding[i];
// We don't rebind references bound to a non-matching version of a reference that was explicitly
// specified, even if we have a better version now.
if (binding.IsBound)
{
continue;
}
// We only need to resolve against implicitly resolved assemblies,
// since we already resolved against explicitly specified ones.
Debug.Assert(binding.ReferenceIdentity is object);
referenceBinding[i] = ResolveReferencedAssembly(
binding.ReferenceIdentity,
allAssemblies,
explicitAssemblyCount,
IdentityComparer);
}
}
UpdateBindingsOfAssemblyBeingBuilt(referenceBindings, explicitAssemblyCount, implicitAssemblies);
metadataReferences = metadataReferencesBuilder.ToImmutable();
resolvedReferences = ToResolvedAssemblyReferences(metadataReferences, lazyAliasMap, explicitAssemblyCount);
}
finally
{
implicitAssemblies.Free();
referenceBindingsToProcess.Free();
metadataReferencesBuilder.Free();
resolutionFailures.Free();
}
}
private void GetInitialReferenceBindingsToProcess(
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings,
int totalReferencedAssemblyCount,
[Out] ArrayBuilder<(MetadataReference, ArraySegment<AssemblyReferenceBinding>)> result)
{
Debug.Assert(result.Count == 0);
// maps module index to explicitReferences index
var explicitModuleToReferenceMap = CalculateModuleToReferenceMap(explicitModules, explicitReferenceMap);
// add module bindings of assembly being built:
var bindingsOfAssemblyBeingBuilt = referenceBindings[0];
int bindingIndex = totalReferencedAssemblyCount;
for (int moduleIndex = 0; moduleIndex < explicitModules.Length; moduleIndex++)
{
var moduleReference = explicitReferences[explicitModuleToReferenceMap[moduleIndex]];
var moduleBindingsCount = explicitModules[moduleIndex].ReferencedAssemblies.Length;
result.Add(
(moduleReference,
new ArraySegment<AssemblyReferenceBinding>(bindingsOfAssemblyBeingBuilt, bindingIndex, moduleBindingsCount)));
bindingIndex += moduleBindingsCount;
}
Debug.Assert(bindingIndex == bindingsOfAssemblyBeingBuilt.Length);
// the first binding is for the assembly being built, all its references are bound or added above
for (int referenceIndex = 0; referenceIndex < explicitReferenceMap.Length; referenceIndex++)
{
var explicitReferenceMapping = explicitReferenceMap[referenceIndex];
if (explicitReferenceMapping.IsSkipped || explicitReferenceMapping.Kind == MetadataImageKind.Module)
{
continue;
}
// +1 for the assembly being built
result.Add(
(explicitReferences[referenceIndex],
new ArraySegment<AssemblyReferenceBinding>(referenceBindings[explicitReferenceMapping.Index + 1])));
}
// we have a reference binding for each module and for each referenced assembly:
Debug.Assert(result.Count == explicitModules.Length + totalReferencedAssemblyCount);
}
private static ImmutableArray<int> CalculateModuleToReferenceMap(ImmutableArray<PEModule> modules, ImmutableArray<ResolvedReference> resolvedReferences)
{
if (modules.Length == 0)
{
return ImmutableArray<int>.Empty;
}
var result = ArrayBuilder<int>.GetInstance(modules.Length);
result.ZeroInit(modules.Length);
for (int i = 0; i < resolvedReferences.Length; i++)
{
var resolvedReference = resolvedReferences[i];
if (!resolvedReference.IsSkipped && resolvedReference.Kind == MetadataImageKind.Module)
{
result[resolvedReference.Index] = i;
}
}
return result.ToImmutableAndFree();
}
private static ImmutableArray<ResolvedReference> ToResolvedAssemblyReferences(
ImmutableArray<MetadataReference> references,
Dictionary<MetadataReference, MergedAliases>? propertyMapOpt,
int explicitAssemblyCount)
{
var result = ArrayBuilder<ResolvedReference>.GetInstance(references.Length);
for (int i = 0; i < references.Length; i++)
{
// -1 for assembly being built
result.Add(GetResolvedReferenceAndFreePropertyMapEntry(references[i], explicitAssemblyCount - 1 + i, MetadataImageKind.Assembly, propertyMapOpt));
}
return result.ToImmutableAndFree();
}
private static void UpdateBindingsOfAssemblyBeingBuilt(ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings, int explicitAssemblyCount, ArrayBuilder<AssemblyData> implicitAssemblies)
{
var referenceBindingsOfAssemblyBeingBuilt = referenceBindings[0];
// add implicitly resolved assemblies to the bindings of the assembly being built:
var bindingsOfAssemblyBeingBuilt = ArrayBuilder<AssemblyReferenceBinding>.GetInstance(referenceBindingsOfAssemblyBeingBuilt.Length + implicitAssemblies.Count);
// add bindings for explicitly specified assemblies (-1 for the assembly being built):
bindingsOfAssemblyBeingBuilt.AddRange(referenceBindingsOfAssemblyBeingBuilt, explicitAssemblyCount - 1);
// add bindings for implicitly resolved assemblies:
for (int i = 0; i < implicitAssemblies.Count; i++)
{
bindingsOfAssemblyBeingBuilt.Add(new AssemblyReferenceBinding(implicitAssemblies[i].Identity, explicitAssemblyCount + i));
}
// add bindings for assemblies referenced by modules added to the compilation:
bindingsOfAssemblyBeingBuilt.AddRange(referenceBindingsOfAssemblyBeingBuilt, explicitAssemblyCount - 1, referenceBindingsOfAssemblyBeingBuilt.Length - explicitAssemblyCount + 1);
referenceBindings[0] = bindingsOfAssemblyBeingBuilt.ToArrayAndFree();
}
/// <summary>
/// Resolve <paramref name="referenceIdentity"/> using a given <paramref name="resolver"/>.
///
/// We make sure not to query the resolver for the same identity multiple times (across submissions).
/// Doing so ensures that we don't create multiple assembly symbols within the same chain of script compilations
/// for the same implicitly resolved identity. Failure to do so results in cast errors like "can't convert T to T".
///
/// The method only records successful resolution results by updating <paramref name="implicitReferenceResolutions"/>.
/// Failures are only recorded after all resolution attempts have been completed.
///
/// This approach addresses the following scenario. Consider a script:
/// <code>
/// #r "dir1\a.dll"
/// #r "dir2\b.dll"
/// </code>
/// where both a.dll and b.dll reference x.dll, which is present only in dir2. Let's assume the resolver first
/// attempts to resolve "x" referenced from "dir1\a.dll". The resolver may fail to find the dependency if it only
/// looks up the directory containing the referencing assembly (dir1). If we recorded and this failure immediately
/// we would not call the resolver to resolve "x" within the context of "dir2\b.dll" (or any other referencing assembly).
///
/// This behavior would ensure consistency and if the types from x.dll do leak thru to the script compilation, but it
/// would result in a missing assembly error. By recording the failure after all resolution attempts are complete
/// we also achieve a consistent behavior but are able to bind the reference to "x.dll". Besides, this approach
/// also avoids dependency on the order in which we evaluate the assembly references in the scenario above.
/// In general, the result of the resolution may still depend on the order of #r - if there are different assemblies
/// of the same identity in different directories.
/// </summary>
private bool TryResolveMissingReference(
MetadataReference requestingReference,
AssemblyIdentity referenceIdentity,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
MetadataReferenceResolver resolver,
DiagnosticBag resolutionDiagnostics,
[NotNullWhen(true)] out AssemblyIdentity? resolvedAssemblyIdentity,
[NotNullWhen(true)] out AssemblyMetadata? resolvedAssemblyMetadata,
[NotNullWhen(true)] out PortableExecutableReference? resolvedReference)
{
resolvedAssemblyIdentity = null;
resolvedAssemblyMetadata = null;
bool isNewlyResolvedReference = false;
// Check if we have previously resolved an identity and reuse the previously resolved reference if so.
// Use the resolver to find the missing reference.
// Note that the resolver may return an assembly of a different identity than requested, e.g. a higher version.
if (!implicitReferenceResolutions.TryGetValue(referenceIdentity, out resolvedReference))
{
resolvedReference = resolver.ResolveMissingAssembly(requestingReference, referenceIdentity);
isNewlyResolvedReference = true;
}
if (resolvedReference == null)
{
return false;
}
resolvedAssemblyMetadata = GetAssemblyMetadata(resolvedReference, resolutionDiagnostics);
if (resolvedAssemblyMetadata == null)
{
return false;
}
var resolvedAssembly = resolvedAssemblyMetadata.GetAssembly();
Debug.Assert(resolvedAssembly is object);
// Allow reference and definition identities to differ in version, but not other properties.
// Don't need to compare if we are reusing a previously resolved reference.
if (isNewlyResolvedReference &&
IdentityComparer.Compare(referenceIdentity, resolvedAssembly.Identity) == AssemblyIdentityComparer.ComparisonResult.NotEquivalent)
{
return false;
}
resolvedAssemblyIdentity = resolvedAssembly.Identity;
implicitReferenceResolutions = implicitReferenceResolutions.Add(referenceIdentity, resolvedReference);
return true;
}
private AssemblyData CreateAssemblyDataForResolvedMissingAssembly(
AssemblyMetadata assemblyMetadata,
PortableExecutableReference peReference,
MetadataImportOptions importOptions)
{
var assembly = assemblyMetadata.GetAssembly();
Debug.Assert(assembly is object);
return CreateAssemblyDataForFile(
assembly,
assemblyMetadata.CachedSymbols,
peReference.DocumentationProvider,
SimpleAssemblyName,
importOptions,
peReference.Properties.EmbedInteropTypes);
}
private bool ReuseAssemblySymbolsWithNoPiaLocalTypes(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray<AssemblyData> assemblies, int corLibraryIndex)
{
int totalAssemblies = assemblies.Length;
for (int i = 1; i < totalAssemblies; i++)
{
if (!assemblies[i].ContainsNoPiaLocalTypes)
{
continue;
}
foreach (TAssemblySymbol candidateAssembly in assemblies[i].AvailableSymbols)
{
// Candidate should be referenced the same way (/r or /l) by the compilation,
// which originated the symbols. We need this restriction in order to prevent
// non-interface generic types closed over NoPia local types from crossing
// assembly boundaries.
if (IsLinked(candidateAssembly) != assemblies[i].IsLinked)
{
continue;
}
ImmutableArray<TAssemblySymbol> resolutionAssemblies = GetNoPiaResolutionAssemblies(candidateAssembly);
if (resolutionAssemblies.IsDefault)
{
continue;
}
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// In order to reuse candidateAssembly, we need to make sure that
// 1) all assemblies in resolutionAssemblies are among assemblies represented
// by assemblies array.
// 2) From assemblies represented by assemblies array all assemblies, except
// assemblyBeingBuilt are among resolutionAssemblies.
bool match = true;
foreach (TAssemblySymbol assembly in resolutionAssemblies)
{
match = false;
for (int j = 1; j < totalAssemblies; j++)
{
if (assemblies[j].IsMatchingAssembly(assembly) &&
IsLinked(assembly) == assemblies[j].IsLinked)
{
candidateInputAssemblySymbols[j] = assembly;
match = true;
// We could break out of the loop unless assemblies array
// can contain duplicate values. Let's play safe and loop
// through all items.
}
}
if (!match)
{
// Requirement #1 is not met.
break;
}
}
if (!match)
{
continue;
}
for (int j = 1; j < totalAssemblies; j++)
{
if (candidateInputAssemblySymbols[j] == null)
{
// Requirement #2 is not met.
match = false;
break;
}
else
{
// Let's check if different assembly is used as the COR library.
// It shouldn't be possible to get in this situation, but let's play safe.
if (corLibraryIndex < 0)
{
// we don't have COR library.
if (GetCorLibrary(candidateInputAssemblySymbols[j]) != null)
{
// but this assembly has
// I am leaving the Assert here because it will likely indicate a bug somewhere.
Debug.Assert(GetCorLibrary(candidateInputAssemblySymbols[j]) == null);
match = false;
break;
}
}
else
{
// We can't be compiling corlib and have a corlib reference at the same time:
Debug.Assert(corLibraryIndex != 0);
// We have COR library, it should match COR library of the candidate.
if (!ReferenceEquals(candidateInputAssemblySymbols[corLibraryIndex], GetCorLibrary(candidateInputAssemblySymbols[j])))
{
// I am leaving the Assert here because it will likely indicate a bug somewhere.
Debug.Assert(candidateInputAssemblySymbols[corLibraryIndex] == null);
match = false;
break;
}
}
}
}
if (match)
{
// We found a match, use it.
for (int j = 1; j < totalAssemblies; j++)
{
Debug.Assert(candidateInputAssemblySymbols[j] != null);
boundInputs[j].AssemblySymbol = candidateInputAssemblySymbols[j];
}
return true;
}
}
// Prepare candidateMatchingSymbols for next operations.
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// Why it doesn't make sense to examine other assemblies with local types?
// Since we couldn't find a suitable match for this assembly,
// we know that requirement #2 cannot be met for any other assembly
// containing local types.
break;
}
return false;
}
private void ReuseAssemblySymbols(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray<AssemblyData> assemblies, int corLibraryIndex)
{
// Queue of references we need to examine for consistency
Queue<AssemblyReferenceCandidate> candidatesToExamine = new Queue<AssemblyReferenceCandidate>();
int totalAssemblies = assemblies.Length;
// A reusable buffer to contain the AssemblySymbols a candidate symbol refers to
// ⚠ PERF: https://github.com/dotnet/roslyn/issues/47471
List<TAssemblySymbol?> candidateReferencedSymbols = new List<TAssemblySymbol?>(1024);
for (int i = 1; i < totalAssemblies; i++)
{
// We could have a match already
if (boundInputs[i].AssemblySymbol != null || assemblies[i].ContainsNoPiaLocalTypes)
{
continue;
}
foreach (TAssemblySymbol candidateAssembly in assemblies[i].AvailableSymbols)
{
bool match = true;
// We should examine this candidate, all its references that are supposed to
// match one of the given assemblies and do the same for their references, etc.
// The whole set of symbols we get at the end should be consistent with the set
// of assemblies we are given. The whole set of symbols should be accepted or rejected.
// The set of symbols is accumulated in candidateInputAssemblySymbols. It is merged into
// boundInputs after consistency is confirmed.
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// Symbols and index of the corresponding assembly to match against are accumulated in the
// candidatesToExamine queue. They are examined one by one.
candidatesToExamine.Clear();
// This is a queue of symbols that we are picking up as a result of using
// symbols from candidateAssembly
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(i, candidateAssembly));
while (match && candidatesToExamine.Count > 0)
{
AssemblyReferenceCandidate candidate = candidatesToExamine.Dequeue();
Debug.Assert(candidate.DefinitionIndex >= 0);
Debug.Assert(candidate.AssemblySymbol is object);
int candidateIndex = candidate.DefinitionIndex;
// Have we already chosen symbols for the corresponding assembly?
Debug.Assert(boundInputs[candidateIndex].AssemblySymbol == null ||
candidateInputAssemblySymbols[candidateIndex] == null);
TAssemblySymbol? inputAssembly = boundInputs[candidateIndex].AssemblySymbol;
if (inputAssembly == null)
{
inputAssembly = candidateInputAssemblySymbols[candidateIndex];
}
if (inputAssembly != null)
{
if (Object.ReferenceEquals(inputAssembly, candidate.AssemblySymbol))
{
// We already checked this AssemblySymbol, no reason to check it again
continue; // Proceed with the next assembly in candidatesToExamine queue.
}
// We are using different AssemblySymbol for this assembly
match = false;
break; // Stop processing items from candidatesToExamine queue.
}
// Candidate should be referenced the same way (/r or /l) by the compilation,
// which originated the symbols. We need this restriction in order to prevent
// non-interface generic types closed over NoPia local types from crossing
// assembly boundaries.
if (IsLinked(candidate.AssemblySymbol) != assemblies[candidateIndex].IsLinked)
{
match = false;
break; // Stop processing items from candidatesToExamine queue.
}
// Add symbols to the set at corresponding index
Debug.Assert(candidateInputAssemblySymbols[candidateIndex] == null);
candidateInputAssemblySymbols[candidateIndex] = candidate.AssemblySymbol;
// Now process references of the candidate.
// how we bound the candidate references for this compilation:
var candidateReferenceBinding = boundInputs[candidateIndex].ReferenceBinding;
// get the AssemblySymbols the candidate symbol refers to into candidateReferencedSymbols
candidateReferencedSymbols.Clear();
GetActualBoundReferencesUsedBy(candidate.AssemblySymbol, candidateReferencedSymbols);
Debug.Assert(candidateReferenceBinding is object);
Debug.Assert(candidateReferenceBinding.Length == candidateReferencedSymbols.Count);
int referencesCount = candidateReferencedSymbols.Count;
for (int k = 0; k < referencesCount; k++)
{
// All candidate's references that were /l-ed by the compilation,
// which originated the symbols, must be /l-ed by this compilation and
// other references must be either /r-ed or not referenced.
// We need this restriction in order to prevent non-interface generic types
// closed over NoPia local types from crossing assembly boundaries.
// if target reference isn't resolved against given assemblies,
// we cannot accept a candidate that has the reference resolved.
if (!candidateReferenceBinding[k].IsBound)
{
if (candidateReferencedSymbols[k] != null)
{
// can't use symbols
// If we decide do go back to accepting references like this,
// we should still not do this if the reference is a /l-ed assembly.
match = false;
break; // Stop processing references.
}
continue; // Proceed with the next reference.
}
// We resolved the reference, candidate must have that reference resolved too.
var currentCandidateReferencedSymbol = candidateReferencedSymbols[k];
if (currentCandidateReferencedSymbol == null)
{
// can't use symbols
match = false;
break; // Stop processing references.
}
int definitionIndex = candidateReferenceBinding[k].DefinitionIndex;
if (definitionIndex == 0)
{
// We can't reuse any assembly that refers to the assembly being built.
match = false;
break;
}
// Make sure symbols represent the same assembly/binary
if (!assemblies[definitionIndex].IsMatchingAssembly(currentCandidateReferencedSymbol))
{
// Mismatch between versions?
match = false;
break; // Stop processing references.
}
if (assemblies[definitionIndex].ContainsNoPiaLocalTypes)
{
// We already know that we cannot reuse any existing symbols for
// this assembly
match = false;
break; // Stop processing references.
}
if (IsLinked(currentCandidateReferencedSymbol) != assemblies[definitionIndex].IsLinked)
{
// Mismatch between reference kind.
match = false;
break; // Stop processing references.
}
// Add this reference to the queue so that we consider it as a candidate too
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(definitionIndex, currentCandidateReferencedSymbol));
}
// Check that the COR library used by the candidate assembly symbol is the same as the one use by this compilation.
if (match)
{
TAssemblySymbol? candidateCorLibrary = GetCorLibrary(candidate.AssemblySymbol);
if (candidateCorLibrary == null)
{
// If the candidate didn't have a COR library, that is fine as long as we don't have one either.
if (corLibraryIndex >= 0)
{
match = false;
break; // Stop processing references.
}
}
else
{
// We can't be compiling corlib and have a corlib reference at the same time:
Debug.Assert(corLibraryIndex != 0);
Debug.Assert(ReferenceEquals(candidateCorLibrary, GetCorLibrary(candidateCorLibrary)));
// Candidate has COR library, we should have one too.
if (corLibraryIndex < 0)
{
match = false;
break; // Stop processing references.
}
// Make sure candidate COR library represent the same assembly/binary
if (!assemblies[corLibraryIndex].IsMatchingAssembly(candidateCorLibrary))
{
// Mismatch between versions?
match = false;
break; // Stop processing references.
}
Debug.Assert(!assemblies[corLibraryIndex].ContainsNoPiaLocalTypes);
Debug.Assert(!assemblies[corLibraryIndex].IsLinked);
Debug.Assert(!IsLinked(candidateCorLibrary));
// Add the candidate COR library to the queue so that we consider it as a candidate.
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(corLibraryIndex, candidateCorLibrary));
}
}
}
if (match)
{
// Merge the set of symbols into result
for (int k = 0; k < totalAssemblies; k++)
{
if (candidateInputAssemblySymbols[k] != null)
{
Debug.Assert(boundInputs[k].AssemblySymbol == null);
boundInputs[k].AssemblySymbol = candidateInputAssemblySymbols[k];
}
}
// No reason to examine other symbols for this assembly
break; // Stop processing assemblies[i].AvailableSymbols
}
}
}
}
private static bool CheckCircularReference(IReadOnlyList<AssemblyReferenceBinding[]> referenceBindings)
{
for (int i = 1; i < referenceBindings.Count; i++)
{
foreach (AssemblyReferenceBinding index in referenceBindings[i])
{
if (index.BoundToAssemblyBeingBuilt)
{
return true;
}
}
}
return false;
}
private static bool IsSuperseded(AssemblyIdentity identity, IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName)
{
var value = assemblyReferencesBySimpleName[identity.Name][0];
Debug.Assert(value.Identity is object);
return value.Identity.Version != identity.Version;
}
private static int IndexOfCorLibrary(ImmutableArray<AssemblyData> assemblies, IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, bool supersedeLowerVersions)
{
// Figure out COR library for this compilation.
ArrayBuilder<int>? corLibraryCandidates = null;
for (int i = 1; i < assemblies.Length; i++)
{
var assembly = assemblies[i];
// The logic about deciding what assembly is a candidate for being a Cor library here and in
// Microsoft.CodeAnalysis.VisualBasic.CommandLineCompiler.ResolveMetadataReferencesFromArguments
// should be equivalent.
// Linked references cannot be used as COR library.
// References containing NoPia local types also cannot be used as COR library.
if (!assembly.IsLinked &&
assembly.AssemblyReferences.Length == 0 &&
!assembly.ContainsNoPiaLocalTypes &&
(!supersedeLowerVersions || !IsSuperseded(assembly.Identity, assemblyReferencesBySimpleName)))
{
// We have referenced assembly that doesn't have assembly references,
// check if it declares baseless System.Object.
if (assembly.DeclaresTheObjectClass)
{
if (corLibraryCandidates == null)
{
corLibraryCandidates = ArrayBuilder<int>.GetInstance();
}
// This could be the COR library.
corLibraryCandidates.Add(i);
}
}
}
// If there is an ambiguous match, pretend there is no COR library.
// TODO: figure out if we need to be able to resolve this ambiguity.
if (corLibraryCandidates != null)
{
if (corLibraryCandidates.Count == 1)
{
// TODO: need to make sure we error if such assembly declares local type in source.
int result = corLibraryCandidates[0];
corLibraryCandidates.Free();
return result;
}
else
{
// TODO: C# seems to pick the first one (but produces warnings when looking up predefined types).
// See PredefinedTypes::Init(ErrorHandling*).
corLibraryCandidates.Free();
}
}
// If we have assembly being built and no references,
// assume the assembly we are building is the COR library.
if (assemblies.Length == 1 && assemblies[0].AssemblyReferences.Length == 0)
{
return 0;
}
return -1;
}
/// <summary>
/// Determines if it is possible that <paramref name="assembly"/> gives internals
/// access to assembly <paramref name="compilationName"/>. It does not make a conclusive
/// determination of visibility because the compilation's strong name key is not supplied.
/// </summary>
internal static bool InternalsMayBeVisibleToAssemblyBeingCompiled(string compilationName, PEAssembly assembly)
{
return !assembly.GetInternalsVisibleToPublicKeys(compilationName).IsEmpty();
}
// https://github.com/dotnet/roslyn/issues/40751 It should not be necessary to annotate this method to annotate overrides
/// <summary>
/// Compute AssemblySymbols referenced by the input AssemblySymbol and fill in <paramref name="referencedAssemblySymbols"/> with the result.
/// The AssemblySymbols must correspond
/// to the AssemblyNames returned by AssemblyData.AssemblyReferences property. If reference is not
/// resolved, null reference should be returned in the corresponding item.
/// </summary>
/// <param name="assemblySymbol">The target AssemblySymbol instance.</param>
/// <param name="referencedAssemblySymbols">A list which will be filled in with
/// AssemblySymbols referenced by the input AssemblySymbol. The caller is expected to clear
/// the list before calling this method.
/// Implementer may not cache the list; the caller may mutate it.</param>
protected abstract void GetActualBoundReferencesUsedBy(TAssemblySymbol assemblySymbol, List<TAssemblySymbol?> referencedAssemblySymbols);
/// <summary>
/// Return collection of assemblies involved in canonical type resolution of
/// NoPia local types defined within target assembly. In other words, all
/// references used by previous compilation referencing the target assembly.
/// </summary>
protected abstract ImmutableArray<TAssemblySymbol> GetNoPiaResolutionAssemblies(TAssemblySymbol candidateAssembly);
/// <summary>
/// Assembly is /l-ed by compilation that is using it as a reference.
/// </summary>
protected abstract bool IsLinked(TAssemblySymbol candidateAssembly);
/// <summary>
/// Get Assembly used as COR library for the candidate.
/// </summary>
protected abstract TAssemblySymbol? GetCorLibrary(TAssemblySymbol candidateAssembly);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// For the given set of AssemblyData objects, do the following:
/// 1) Resolve references from each assembly against other assemblies in the set.
/// 2) Choose suitable AssemblySymbol instance for each AssemblyData object.
///
/// The first element (index==0) of the assemblies array represents the assembly being built.
/// One can think about the rest of the items in assemblies array as assembly references given to the compiler to
/// build executable for the assembly being built.
/// </summary>
/// <param name="compilation">Compilation.</param>
/// <param name="explicitAssemblies">
/// An array of <see cref="AssemblyData"/> objects describing assemblies, for which this method should
/// resolve references and find suitable AssemblySymbols. The first slot contains the assembly being built.
/// </param>
/// <param name="explicitModules">
/// An array of <see cref="PEModule"/> objects describing standalone modules referenced by the compilation.
/// </param>
/// <param name="explicitReferences">
/// An array of references passed to the compilation and resolved from #r directives.
/// May contain references that were skipped during resolution (they don't have a corresponding explicit assembly).
/// </param>
/// <param name="explicitReferenceMap">
/// Maps index to <paramref name="explicitReferences"/> to an index of a resolved assembly or module in <paramref name="explicitAssemblies"/> or modules.
/// </param>
/// <param name="resolverOpt">
/// Reference resolver used to look up missing assemblies.
/// </param>
/// <param name="supersedeLowerVersions">
/// Hide lower versions of dependencies that have multiple versions behind an alias.
/// </param>
/// <param name="assemblyReferencesBySimpleName">
/// Used to filter out assemblies that have the same strong or weak identity.
/// Maps simple name to a list of identities. The highest version of each name is the first.
/// </param>
/// <param name="importOptions">
/// Import options applied to implicitly resolved references.
/// </param>
/// <param name="allAssemblies">
/// Updated array <paramref name="explicitAssemblies"/> with resolved implicitly referenced assemblies appended.
/// </param>
/// <param name="implicitlyResolvedReferences">
/// Implicitly resolved references.
/// </param>
/// <param name="implicitlyResolvedReferenceMap">
/// Maps indices of implicitly resolved references to the corresponding indices of resolved assemblies in <paramref name="allAssemblies"/> (explicit + implicit).
/// </param>
/// <param name="implicitReferenceResolutions">
/// Map of implicit reference resolutions performed in the preceding script compilation.
/// Output contains additional implicit resolutions performed during binding of this script compilation references.
/// </param>
/// <param name="resolutionDiagnostics">
/// Any diagnostics reported while resolving missing assemblies.
/// </param>
/// <param name="hasCircularReference">
/// True if the assembly being compiled is indirectly referenced through some of its own references.
/// </param>
/// <param name="corLibraryIndex">
/// The definition index of the COR library.
/// </param>
/// <return>
/// An array of <see cref="BoundInputAssembly"/> structures describing the result. It has the same amount of items as
/// the input assemblies array, <see cref="BoundInputAssembly"/> for each input AssemblyData object resides
/// at the same position.
///
/// Each <see cref="BoundInputAssembly"/> contains the following data:
///
/// - Suitable AssemblySymbol instance for the corresponding assembly,
/// null reference if none is available/found. Always null for the first element, which corresponds to the assembly being built.
///
/// - Result of resolving assembly references of the corresponding assembly
/// against provided set of assembly definitions. Essentially, this is an array returned by
/// <see cref="AssemblyData.BindAssemblyReferences(ImmutableArray{AssemblyData}, AssemblyIdentityComparer)"/> method.
/// </return>
protected BoundInputAssembly[] Bind(
TCompilation compilation,
ImmutableArray<AssemblyData> explicitAssemblies,
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
MetadataReferenceResolver? resolverOpt,
MetadataImportOptions importOptions,
bool supersedeLowerVersions,
[In, Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<AssemblyData> allAssemblies,
out ImmutableArray<MetadataReference> implicitlyResolvedReferences,
out ImmutableArray<ResolvedReference> implicitlyResolvedReferenceMap,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
[In, Out] DiagnosticBag resolutionDiagnostics,
out bool hasCircularReference,
out int corLibraryIndex)
{
Debug.Assert(explicitAssemblies[0] is AssemblyDataForAssemblyBeingBuilt);
Debug.Assert(explicitReferences.Length == explicitReferenceMap.Length);
var referenceBindings = ArrayBuilder<AssemblyReferenceBinding[]>.GetInstance();
try
{
// Based on assembly identity, for each assembly,
// bind its references against the other assemblies we have.
for (int i = 0; i < explicitAssemblies.Length; i++)
{
referenceBindings.Add(explicitAssemblies[i].BindAssemblyReferences(explicitAssemblies, IdentityComparer));
}
if (resolverOpt?.ResolveMissingAssemblies == true)
{
ResolveAndBindMissingAssemblies(
compilation,
explicitAssemblies,
explicitModules,
explicitReferences,
explicitReferenceMap,
resolverOpt,
importOptions,
supersedeLowerVersions,
referenceBindings,
assemblyReferencesBySimpleName,
out allAssemblies,
out implicitlyResolvedReferences,
out implicitlyResolvedReferenceMap,
ref implicitReferenceResolutions,
resolutionDiagnostics);
}
else
{
allAssemblies = explicitAssemblies;
implicitlyResolvedReferences = ImmutableArray<MetadataReference>.Empty;
implicitlyResolvedReferenceMap = ImmutableArray<ResolvedReference>.Empty;
}
// implicitly resolved missing assemblies were added to both referenceBindings and assemblies:
Debug.Assert(referenceBindings.Count == allAssemblies.Length);
hasCircularReference = CheckCircularReference(referenceBindings);
corLibraryIndex = IndexOfCorLibrary(explicitAssemblies, assemblyReferencesBySimpleName, supersedeLowerVersions);
// For each assembly, locate AssemblySymbol with similar reference resolution
// What does similar mean?
// Similar means:
// 1) The same references are resolved against the assemblies that we are given
// (or were found during implicit assembly resolution).
// 2) The same assembly is used as the COR library.
var boundInputs = new BoundInputAssembly[referenceBindings.Count];
for (int i = 0; i < referenceBindings.Count; i++)
{
boundInputs[i].ReferenceBinding = referenceBindings[i];
}
var candidateInputAssemblySymbols = new TAssemblySymbol[allAssemblies.Length];
// If any assembly from assemblies array refers back to assemblyBeingBuilt,
// we know that we cannot reuse symbols for any assemblies containing NoPia
// local types. Because we cannot reuse symbols for assembly referring back
// to assemblyBeingBuilt.
if (!hasCircularReference)
{
// Deal with assemblies containing NoPia local types.
if (ReuseAssemblySymbolsWithNoPiaLocalTypes(boundInputs, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex))
{
return boundInputs;
}
}
// NoPia shortcut either didn't apply or failed, go through general process
// of matching candidates.
ReuseAssemblySymbols(boundInputs, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex);
return boundInputs;
}
finally
{
referenceBindings.Free();
}
}
private void ResolveAndBindMissingAssemblies(
TCompilation compilation,
ImmutableArray<AssemblyData> explicitAssemblies,
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
MetadataReferenceResolver resolver,
MetadataImportOptions importOptions,
bool supersedeLowerVersions,
[In, Out] ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings,
[In, Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<AssemblyData> allAssemblies,
out ImmutableArray<MetadataReference> metadataReferences,
out ImmutableArray<ResolvedReference> resolvedReferences,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
DiagnosticBag resolutionDiagnostics)
{
Debug.Assert(explicitAssemblies[0] is AssemblyDataForAssemblyBeingBuilt);
Debug.Assert(referenceBindings.Count == explicitAssemblies.Length);
Debug.Assert(explicitReferences.Length == explicitReferenceMap.Length);
// -1 for assembly being built:
int totalReferencedAssemblyCount = explicitAssemblies.Length - 1;
var implicitAssemblies = ArrayBuilder<AssemblyData>.GetInstance();
// assembly identities whose resolution failed for all attempted requesting references:
var resolutionFailures = PooledHashSet<AssemblyIdentity>.GetInstance();
var metadataReferencesBuilder = ArrayBuilder<MetadataReference>.GetInstance();
Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null;
// metadata references and corresponding bindings of their references, used to calculate a fixed point:
var referenceBindingsToProcess = ArrayBuilder<(MetadataReference, ArraySegment<AssemblyReferenceBinding>)>.GetInstance();
// collect all missing identities, resolve the assemblies and bind their references against explicit definitions:
GetInitialReferenceBindingsToProcess(explicitModules, explicitReferences, explicitReferenceMap, referenceBindings, totalReferencedAssemblyCount, referenceBindingsToProcess);
// NB: includes the assembly being built:
int explicitAssemblyCount = explicitAssemblies.Length;
try
{
while (referenceBindingsToProcess.Count > 0)
{
var (requestingReference, bindings) = referenceBindingsToProcess.Pop();
foreach (var binding in bindings)
{
// only attempt to resolve unbound references (regardless of version difference of the bound ones)
if (binding.IsBound)
{
continue;
}
Debug.Assert(binding.ReferenceIdentity is object);
if (!TryResolveMissingReference(
requestingReference,
binding.ReferenceIdentity,
ref implicitReferenceResolutions,
resolver,
resolutionDiagnostics,
out AssemblyIdentity? resolvedAssemblyIdentity,
out AssemblyMetadata? resolvedAssemblyMetadata,
out PortableExecutableReference? resolvedReference))
{
// Note the failure, but do not commit it to implicitReferenceResolutions until we are done with resolving all missing references.
resolutionFailures.Add(binding.ReferenceIdentity);
continue;
}
// One attempt for resolution succeeded. The attempt is cached in implicitReferenceResolutions, so further attempts won't fail and add it back.
// Since the failures tracked in resolutionFailures do not affect binding there is no need to revert any decisions made so far.
resolutionFailures.Remove(binding.ReferenceIdentity);
// The resolver may return different version than we asked for, so it may happen that
// it returns the same identity for two different input identities (e.g. if a higher version
// of an assembly is available than what the assemblies reference: "A, v1" -> "A, v3" and "A, v2" -> "A, v3").
// If such case occurs merge the properties (aliases) of the resulting references in the same way we do
// during initial explicit references resolution.
// -1 for assembly being built:
int index = explicitAssemblyCount - 1 + metadataReferencesBuilder.Count;
var existingReference = TryAddAssembly(resolvedAssemblyIdentity, resolvedReference, index, resolutionDiagnostics, Location.None, assemblyReferencesBySimpleName, supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, resolvedReference, resolutionDiagnostics, ref lazyAliasMap);
continue;
}
metadataReferencesBuilder.Add(resolvedReference);
var data = CreateAssemblyDataForResolvedMissingAssembly(resolvedAssemblyMetadata, resolvedReference, importOptions);
implicitAssemblies.Add(data);
var referenceBinding = data.BindAssemblyReferences(explicitAssemblies, IdentityComparer);
referenceBindings.Add(referenceBinding);
referenceBindingsToProcess.Push((resolvedReference, new ArraySegment<AssemblyReferenceBinding>(referenceBinding)));
}
}
// record failures for resolution in subsequent submissions:
foreach (var assemblyIdentity in resolutionFailures)
{
implicitReferenceResolutions = implicitReferenceResolutions.Add(assemblyIdentity, null);
}
if (implicitAssemblies.Count == 0)
{
Debug.Assert(lazyAliasMap == null);
resolvedReferences = ImmutableArray<ResolvedReference>.Empty;
metadataReferences = ImmutableArray<MetadataReference>.Empty;
allAssemblies = explicitAssemblies;
return;
}
// Rebind assembly references that were initially missing. All bindings established above
// are against explicitly specified references.
allAssemblies = explicitAssemblies.AddRange(implicitAssemblies);
for (int bindingsIndex = 0; bindingsIndex < referenceBindings.Count; bindingsIndex++)
{
var referenceBinding = referenceBindings[bindingsIndex];
for (int i = 0; i < referenceBinding.Length; i++)
{
var binding = referenceBinding[i];
// We don't rebind references bound to a non-matching version of a reference that was explicitly
// specified, even if we have a better version now.
if (binding.IsBound)
{
continue;
}
// We only need to resolve against implicitly resolved assemblies,
// since we already resolved against explicitly specified ones.
Debug.Assert(binding.ReferenceIdentity is object);
referenceBinding[i] = ResolveReferencedAssembly(
binding.ReferenceIdentity,
allAssemblies,
explicitAssemblyCount,
IdentityComparer);
}
}
UpdateBindingsOfAssemblyBeingBuilt(referenceBindings, explicitAssemblyCount, implicitAssemblies);
metadataReferences = metadataReferencesBuilder.ToImmutable();
resolvedReferences = ToResolvedAssemblyReferences(metadataReferences, lazyAliasMap, explicitAssemblyCount);
}
finally
{
implicitAssemblies.Free();
referenceBindingsToProcess.Free();
metadataReferencesBuilder.Free();
resolutionFailures.Free();
}
}
private void GetInitialReferenceBindingsToProcess(
ImmutableArray<PEModule> explicitModules,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableArray<ResolvedReference> explicitReferenceMap,
ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings,
int totalReferencedAssemblyCount,
[Out] ArrayBuilder<(MetadataReference, ArraySegment<AssemblyReferenceBinding>)> result)
{
Debug.Assert(result.Count == 0);
// maps module index to explicitReferences index
var explicitModuleToReferenceMap = CalculateModuleToReferenceMap(explicitModules, explicitReferenceMap);
// add module bindings of assembly being built:
var bindingsOfAssemblyBeingBuilt = referenceBindings[0];
int bindingIndex = totalReferencedAssemblyCount;
for (int moduleIndex = 0; moduleIndex < explicitModules.Length; moduleIndex++)
{
var moduleReference = explicitReferences[explicitModuleToReferenceMap[moduleIndex]];
var moduleBindingsCount = explicitModules[moduleIndex].ReferencedAssemblies.Length;
result.Add(
(moduleReference,
new ArraySegment<AssemblyReferenceBinding>(bindingsOfAssemblyBeingBuilt, bindingIndex, moduleBindingsCount)));
bindingIndex += moduleBindingsCount;
}
Debug.Assert(bindingIndex == bindingsOfAssemblyBeingBuilt.Length);
// the first binding is for the assembly being built, all its references are bound or added above
for (int referenceIndex = 0; referenceIndex < explicitReferenceMap.Length; referenceIndex++)
{
var explicitReferenceMapping = explicitReferenceMap[referenceIndex];
if (explicitReferenceMapping.IsSkipped || explicitReferenceMapping.Kind == MetadataImageKind.Module)
{
continue;
}
// +1 for the assembly being built
result.Add(
(explicitReferences[referenceIndex],
new ArraySegment<AssemblyReferenceBinding>(referenceBindings[explicitReferenceMapping.Index + 1])));
}
// we have a reference binding for each module and for each referenced assembly:
Debug.Assert(result.Count == explicitModules.Length + totalReferencedAssemblyCount);
}
private static ImmutableArray<int> CalculateModuleToReferenceMap(ImmutableArray<PEModule> modules, ImmutableArray<ResolvedReference> resolvedReferences)
{
if (modules.Length == 0)
{
return ImmutableArray<int>.Empty;
}
var result = ArrayBuilder<int>.GetInstance(modules.Length);
result.ZeroInit(modules.Length);
for (int i = 0; i < resolvedReferences.Length; i++)
{
var resolvedReference = resolvedReferences[i];
if (!resolvedReference.IsSkipped && resolvedReference.Kind == MetadataImageKind.Module)
{
result[resolvedReference.Index] = i;
}
}
return result.ToImmutableAndFree();
}
private static ImmutableArray<ResolvedReference> ToResolvedAssemblyReferences(
ImmutableArray<MetadataReference> references,
Dictionary<MetadataReference, MergedAliases>? propertyMapOpt,
int explicitAssemblyCount)
{
var result = ArrayBuilder<ResolvedReference>.GetInstance(references.Length);
for (int i = 0; i < references.Length; i++)
{
// -1 for assembly being built
result.Add(GetResolvedReferenceAndFreePropertyMapEntry(references[i], explicitAssemblyCount - 1 + i, MetadataImageKind.Assembly, propertyMapOpt));
}
return result.ToImmutableAndFree();
}
private static void UpdateBindingsOfAssemblyBeingBuilt(ArrayBuilder<AssemblyReferenceBinding[]> referenceBindings, int explicitAssemblyCount, ArrayBuilder<AssemblyData> implicitAssemblies)
{
var referenceBindingsOfAssemblyBeingBuilt = referenceBindings[0];
// add implicitly resolved assemblies to the bindings of the assembly being built:
var bindingsOfAssemblyBeingBuilt = ArrayBuilder<AssemblyReferenceBinding>.GetInstance(referenceBindingsOfAssemblyBeingBuilt.Length + implicitAssemblies.Count);
// add bindings for explicitly specified assemblies (-1 for the assembly being built):
bindingsOfAssemblyBeingBuilt.AddRange(referenceBindingsOfAssemblyBeingBuilt, explicitAssemblyCount - 1);
// add bindings for implicitly resolved assemblies:
for (int i = 0; i < implicitAssemblies.Count; i++)
{
bindingsOfAssemblyBeingBuilt.Add(new AssemblyReferenceBinding(implicitAssemblies[i].Identity, explicitAssemblyCount + i));
}
// add bindings for assemblies referenced by modules added to the compilation:
bindingsOfAssemblyBeingBuilt.AddRange(referenceBindingsOfAssemblyBeingBuilt, explicitAssemblyCount - 1, referenceBindingsOfAssemblyBeingBuilt.Length - explicitAssemblyCount + 1);
referenceBindings[0] = bindingsOfAssemblyBeingBuilt.ToArrayAndFree();
}
/// <summary>
/// Resolve <paramref name="referenceIdentity"/> using a given <paramref name="resolver"/>.
///
/// We make sure not to query the resolver for the same identity multiple times (across submissions).
/// Doing so ensures that we don't create multiple assembly symbols within the same chain of script compilations
/// for the same implicitly resolved identity. Failure to do so results in cast errors like "can't convert T to T".
///
/// The method only records successful resolution results by updating <paramref name="implicitReferenceResolutions"/>.
/// Failures are only recorded after all resolution attempts have been completed.
///
/// This approach addresses the following scenario. Consider a script:
/// <code>
/// #r "dir1\a.dll"
/// #r "dir2\b.dll"
/// </code>
/// where both a.dll and b.dll reference x.dll, which is present only in dir2. Let's assume the resolver first
/// attempts to resolve "x" referenced from "dir1\a.dll". The resolver may fail to find the dependency if it only
/// looks up the directory containing the referencing assembly (dir1). If we recorded and this failure immediately
/// we would not call the resolver to resolve "x" within the context of "dir2\b.dll" (or any other referencing assembly).
///
/// This behavior would ensure consistency and if the types from x.dll do leak thru to the script compilation, but it
/// would result in a missing assembly error. By recording the failure after all resolution attempts are complete
/// we also achieve a consistent behavior but are able to bind the reference to "x.dll". Besides, this approach
/// also avoids dependency on the order in which we evaluate the assembly references in the scenario above.
/// In general, the result of the resolution may still depend on the order of #r - if there are different assemblies
/// of the same identity in different directories.
/// </summary>
private bool TryResolveMissingReference(
MetadataReference requestingReference,
AssemblyIdentity referenceIdentity,
ref ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
MetadataReferenceResolver resolver,
DiagnosticBag resolutionDiagnostics,
[NotNullWhen(true)] out AssemblyIdentity? resolvedAssemblyIdentity,
[NotNullWhen(true)] out AssemblyMetadata? resolvedAssemblyMetadata,
[NotNullWhen(true)] out PortableExecutableReference? resolvedReference)
{
resolvedAssemblyIdentity = null;
resolvedAssemblyMetadata = null;
bool isNewlyResolvedReference = false;
// Check if we have previously resolved an identity and reuse the previously resolved reference if so.
// Use the resolver to find the missing reference.
// Note that the resolver may return an assembly of a different identity than requested, e.g. a higher version.
if (!implicitReferenceResolutions.TryGetValue(referenceIdentity, out resolvedReference))
{
resolvedReference = resolver.ResolveMissingAssembly(requestingReference, referenceIdentity);
isNewlyResolvedReference = true;
}
if (resolvedReference == null)
{
return false;
}
resolvedAssemblyMetadata = GetAssemblyMetadata(resolvedReference, resolutionDiagnostics);
if (resolvedAssemblyMetadata == null)
{
return false;
}
var resolvedAssembly = resolvedAssemblyMetadata.GetAssembly();
Debug.Assert(resolvedAssembly is object);
// Allow reference and definition identities to differ in version, but not other properties.
// Don't need to compare if we are reusing a previously resolved reference.
if (isNewlyResolvedReference &&
IdentityComparer.Compare(referenceIdentity, resolvedAssembly.Identity) == AssemblyIdentityComparer.ComparisonResult.NotEquivalent)
{
return false;
}
resolvedAssemblyIdentity = resolvedAssembly.Identity;
implicitReferenceResolutions = implicitReferenceResolutions.Add(referenceIdentity, resolvedReference);
return true;
}
private AssemblyData CreateAssemblyDataForResolvedMissingAssembly(
AssemblyMetadata assemblyMetadata,
PortableExecutableReference peReference,
MetadataImportOptions importOptions)
{
var assembly = assemblyMetadata.GetAssembly();
Debug.Assert(assembly is object);
return CreateAssemblyDataForFile(
assembly,
assemblyMetadata.CachedSymbols,
peReference.DocumentationProvider,
SimpleAssemblyName,
importOptions,
peReference.Properties.EmbedInteropTypes);
}
private bool ReuseAssemblySymbolsWithNoPiaLocalTypes(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray<AssemblyData> assemblies, int corLibraryIndex)
{
int totalAssemblies = assemblies.Length;
for (int i = 1; i < totalAssemblies; i++)
{
if (!assemblies[i].ContainsNoPiaLocalTypes)
{
continue;
}
foreach (TAssemblySymbol candidateAssembly in assemblies[i].AvailableSymbols)
{
// Candidate should be referenced the same way (/r or /l) by the compilation,
// which originated the symbols. We need this restriction in order to prevent
// non-interface generic types closed over NoPia local types from crossing
// assembly boundaries.
if (IsLinked(candidateAssembly) != assemblies[i].IsLinked)
{
continue;
}
ImmutableArray<TAssemblySymbol> resolutionAssemblies = GetNoPiaResolutionAssemblies(candidateAssembly);
if (resolutionAssemblies.IsDefault)
{
continue;
}
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// In order to reuse candidateAssembly, we need to make sure that
// 1) all assemblies in resolutionAssemblies are among assemblies represented
// by assemblies array.
// 2) From assemblies represented by assemblies array all assemblies, except
// assemblyBeingBuilt are among resolutionAssemblies.
bool match = true;
foreach (TAssemblySymbol assembly in resolutionAssemblies)
{
match = false;
for (int j = 1; j < totalAssemblies; j++)
{
if (assemblies[j].IsMatchingAssembly(assembly) &&
IsLinked(assembly) == assemblies[j].IsLinked)
{
candidateInputAssemblySymbols[j] = assembly;
match = true;
// We could break out of the loop unless assemblies array
// can contain duplicate values. Let's play safe and loop
// through all items.
}
}
if (!match)
{
// Requirement #1 is not met.
break;
}
}
if (!match)
{
continue;
}
for (int j = 1; j < totalAssemblies; j++)
{
if (candidateInputAssemblySymbols[j] == null)
{
// Requirement #2 is not met.
match = false;
break;
}
else
{
// Let's check if different assembly is used as the COR library.
// It shouldn't be possible to get in this situation, but let's play safe.
if (corLibraryIndex < 0)
{
// we don't have COR library.
if (GetCorLibrary(candidateInputAssemblySymbols[j]) != null)
{
// but this assembly has
// I am leaving the Assert here because it will likely indicate a bug somewhere.
Debug.Assert(GetCorLibrary(candidateInputAssemblySymbols[j]) == null);
match = false;
break;
}
}
else
{
// We can't be compiling corlib and have a corlib reference at the same time:
Debug.Assert(corLibraryIndex != 0);
// We have COR library, it should match COR library of the candidate.
if (!ReferenceEquals(candidateInputAssemblySymbols[corLibraryIndex], GetCorLibrary(candidateInputAssemblySymbols[j])))
{
// I am leaving the Assert here because it will likely indicate a bug somewhere.
Debug.Assert(candidateInputAssemblySymbols[corLibraryIndex] == null);
match = false;
break;
}
}
}
}
if (match)
{
// We found a match, use it.
for (int j = 1; j < totalAssemblies; j++)
{
Debug.Assert(candidateInputAssemblySymbols[j] != null);
boundInputs[j].AssemblySymbol = candidateInputAssemblySymbols[j];
}
return true;
}
}
// Prepare candidateMatchingSymbols for next operations.
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// Why it doesn't make sense to examine other assemblies with local types?
// Since we couldn't find a suitable match for this assembly,
// we know that requirement #2 cannot be met for any other assembly
// containing local types.
break;
}
return false;
}
private void ReuseAssemblySymbols(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray<AssemblyData> assemblies, int corLibraryIndex)
{
// Queue of references we need to examine for consistency
Queue<AssemblyReferenceCandidate> candidatesToExamine = new Queue<AssemblyReferenceCandidate>();
int totalAssemblies = assemblies.Length;
// A reusable buffer to contain the AssemblySymbols a candidate symbol refers to
// ⚠ PERF: https://github.com/dotnet/roslyn/issues/47471
List<TAssemblySymbol?> candidateReferencedSymbols = new List<TAssemblySymbol?>(1024);
for (int i = 1; i < totalAssemblies; i++)
{
// We could have a match already
if (boundInputs[i].AssemblySymbol != null || assemblies[i].ContainsNoPiaLocalTypes)
{
continue;
}
foreach (TAssemblySymbol candidateAssembly in assemblies[i].AvailableSymbols)
{
bool match = true;
// We should examine this candidate, all its references that are supposed to
// match one of the given assemblies and do the same for their references, etc.
// The whole set of symbols we get at the end should be consistent with the set
// of assemblies we are given. The whole set of symbols should be accepted or rejected.
// The set of symbols is accumulated in candidateInputAssemblySymbols. It is merged into
// boundInputs after consistency is confirmed.
Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length);
// Symbols and index of the corresponding assembly to match against are accumulated in the
// candidatesToExamine queue. They are examined one by one.
candidatesToExamine.Clear();
// This is a queue of symbols that we are picking up as a result of using
// symbols from candidateAssembly
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(i, candidateAssembly));
while (match && candidatesToExamine.Count > 0)
{
AssemblyReferenceCandidate candidate = candidatesToExamine.Dequeue();
Debug.Assert(candidate.DefinitionIndex >= 0);
Debug.Assert(candidate.AssemblySymbol is object);
int candidateIndex = candidate.DefinitionIndex;
// Have we already chosen symbols for the corresponding assembly?
Debug.Assert(boundInputs[candidateIndex].AssemblySymbol == null ||
candidateInputAssemblySymbols[candidateIndex] == null);
TAssemblySymbol? inputAssembly = boundInputs[candidateIndex].AssemblySymbol;
if (inputAssembly == null)
{
inputAssembly = candidateInputAssemblySymbols[candidateIndex];
}
if (inputAssembly != null)
{
if (Object.ReferenceEquals(inputAssembly, candidate.AssemblySymbol))
{
// We already checked this AssemblySymbol, no reason to check it again
continue; // Proceed with the next assembly in candidatesToExamine queue.
}
// We are using different AssemblySymbol for this assembly
match = false;
break; // Stop processing items from candidatesToExamine queue.
}
// Candidate should be referenced the same way (/r or /l) by the compilation,
// which originated the symbols. We need this restriction in order to prevent
// non-interface generic types closed over NoPia local types from crossing
// assembly boundaries.
if (IsLinked(candidate.AssemblySymbol) != assemblies[candidateIndex].IsLinked)
{
match = false;
break; // Stop processing items from candidatesToExamine queue.
}
// Add symbols to the set at corresponding index
Debug.Assert(candidateInputAssemblySymbols[candidateIndex] == null);
candidateInputAssemblySymbols[candidateIndex] = candidate.AssemblySymbol;
// Now process references of the candidate.
// how we bound the candidate references for this compilation:
var candidateReferenceBinding = boundInputs[candidateIndex].ReferenceBinding;
// get the AssemblySymbols the candidate symbol refers to into candidateReferencedSymbols
candidateReferencedSymbols.Clear();
GetActualBoundReferencesUsedBy(candidate.AssemblySymbol, candidateReferencedSymbols);
Debug.Assert(candidateReferenceBinding is object);
Debug.Assert(candidateReferenceBinding.Length == candidateReferencedSymbols.Count);
int referencesCount = candidateReferencedSymbols.Count;
for (int k = 0; k < referencesCount; k++)
{
// All candidate's references that were /l-ed by the compilation,
// which originated the symbols, must be /l-ed by this compilation and
// other references must be either /r-ed or not referenced.
// We need this restriction in order to prevent non-interface generic types
// closed over NoPia local types from crossing assembly boundaries.
// if target reference isn't resolved against given assemblies,
// we cannot accept a candidate that has the reference resolved.
if (!candidateReferenceBinding[k].IsBound)
{
if (candidateReferencedSymbols[k] != null)
{
// can't use symbols
// If we decide do go back to accepting references like this,
// we should still not do this if the reference is a /l-ed assembly.
match = false;
break; // Stop processing references.
}
continue; // Proceed with the next reference.
}
// We resolved the reference, candidate must have that reference resolved too.
var currentCandidateReferencedSymbol = candidateReferencedSymbols[k];
if (currentCandidateReferencedSymbol == null)
{
// can't use symbols
match = false;
break; // Stop processing references.
}
int definitionIndex = candidateReferenceBinding[k].DefinitionIndex;
if (definitionIndex == 0)
{
// We can't reuse any assembly that refers to the assembly being built.
match = false;
break;
}
// Make sure symbols represent the same assembly/binary
if (!assemblies[definitionIndex].IsMatchingAssembly(currentCandidateReferencedSymbol))
{
// Mismatch between versions?
match = false;
break; // Stop processing references.
}
if (assemblies[definitionIndex].ContainsNoPiaLocalTypes)
{
// We already know that we cannot reuse any existing symbols for
// this assembly
match = false;
break; // Stop processing references.
}
if (IsLinked(currentCandidateReferencedSymbol) != assemblies[definitionIndex].IsLinked)
{
// Mismatch between reference kind.
match = false;
break; // Stop processing references.
}
// Add this reference to the queue so that we consider it as a candidate too
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(definitionIndex, currentCandidateReferencedSymbol));
}
// Check that the COR library used by the candidate assembly symbol is the same as the one use by this compilation.
if (match)
{
TAssemblySymbol? candidateCorLibrary = GetCorLibrary(candidate.AssemblySymbol);
if (candidateCorLibrary == null)
{
// If the candidate didn't have a COR library, that is fine as long as we don't have one either.
if (corLibraryIndex >= 0)
{
match = false;
break; // Stop processing references.
}
}
else
{
// We can't be compiling corlib and have a corlib reference at the same time:
Debug.Assert(corLibraryIndex != 0);
Debug.Assert(ReferenceEquals(candidateCorLibrary, GetCorLibrary(candidateCorLibrary)));
// Candidate has COR library, we should have one too.
if (corLibraryIndex < 0)
{
match = false;
break; // Stop processing references.
}
// Make sure candidate COR library represent the same assembly/binary
if (!assemblies[corLibraryIndex].IsMatchingAssembly(candidateCorLibrary))
{
// Mismatch between versions?
match = false;
break; // Stop processing references.
}
Debug.Assert(!assemblies[corLibraryIndex].ContainsNoPiaLocalTypes);
Debug.Assert(!assemblies[corLibraryIndex].IsLinked);
Debug.Assert(!IsLinked(candidateCorLibrary));
// Add the candidate COR library to the queue so that we consider it as a candidate.
candidatesToExamine.Enqueue(new AssemblyReferenceCandidate(corLibraryIndex, candidateCorLibrary));
}
}
}
if (match)
{
// Merge the set of symbols into result
for (int k = 0; k < totalAssemblies; k++)
{
if (candidateInputAssemblySymbols[k] != null)
{
Debug.Assert(boundInputs[k].AssemblySymbol == null);
boundInputs[k].AssemblySymbol = candidateInputAssemblySymbols[k];
}
}
// No reason to examine other symbols for this assembly
break; // Stop processing assemblies[i].AvailableSymbols
}
}
}
}
private static bool CheckCircularReference(IReadOnlyList<AssemblyReferenceBinding[]> referenceBindings)
{
for (int i = 1; i < referenceBindings.Count; i++)
{
foreach (AssemblyReferenceBinding index in referenceBindings[i])
{
if (index.BoundToAssemblyBeingBuilt)
{
return true;
}
}
}
return false;
}
private static bool IsSuperseded(AssemblyIdentity identity, IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName)
{
var value = assemblyReferencesBySimpleName[identity.Name][0];
Debug.Assert(value.Identity is object);
return value.Identity.Version != identity.Version;
}
private static int IndexOfCorLibrary(ImmutableArray<AssemblyData> assemblies, IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, bool supersedeLowerVersions)
{
// Figure out COR library for this compilation.
ArrayBuilder<int>? corLibraryCandidates = null;
for (int i = 1; i < assemblies.Length; i++)
{
var assembly = assemblies[i];
// The logic about deciding what assembly is a candidate for being a Cor library here and in
// Microsoft.CodeAnalysis.VisualBasic.CommandLineCompiler.ResolveMetadataReferencesFromArguments
// should be equivalent.
// Linked references cannot be used as COR library.
// References containing NoPia local types also cannot be used as COR library.
if (!assembly.IsLinked &&
assembly.AssemblyReferences.Length == 0 &&
!assembly.ContainsNoPiaLocalTypes &&
(!supersedeLowerVersions || !IsSuperseded(assembly.Identity, assemblyReferencesBySimpleName)))
{
// We have referenced assembly that doesn't have assembly references,
// check if it declares baseless System.Object.
if (assembly.DeclaresTheObjectClass)
{
if (corLibraryCandidates == null)
{
corLibraryCandidates = ArrayBuilder<int>.GetInstance();
}
// This could be the COR library.
corLibraryCandidates.Add(i);
}
}
}
// If there is an ambiguous match, pretend there is no COR library.
// TODO: figure out if we need to be able to resolve this ambiguity.
if (corLibraryCandidates != null)
{
if (corLibraryCandidates.Count == 1)
{
// TODO: need to make sure we error if such assembly declares local type in source.
int result = corLibraryCandidates[0];
corLibraryCandidates.Free();
return result;
}
else
{
// TODO: C# seems to pick the first one (but produces warnings when looking up predefined types).
// See PredefinedTypes::Init(ErrorHandling*).
corLibraryCandidates.Free();
}
}
// If we have assembly being built and no references,
// assume the assembly we are building is the COR library.
if (assemblies.Length == 1 && assemblies[0].AssemblyReferences.Length == 0)
{
return 0;
}
return -1;
}
/// <summary>
/// Determines if it is possible that <paramref name="assembly"/> gives internals
/// access to assembly <paramref name="compilationName"/>. It does not make a conclusive
/// determination of visibility because the compilation's strong name key is not supplied.
/// </summary>
internal static bool InternalsMayBeVisibleToAssemblyBeingCompiled(string compilationName, PEAssembly assembly)
{
return !assembly.GetInternalsVisibleToPublicKeys(compilationName).IsEmpty();
}
// https://github.com/dotnet/roslyn/issues/40751 It should not be necessary to annotate this method to annotate overrides
/// <summary>
/// Compute AssemblySymbols referenced by the input AssemblySymbol and fill in <paramref name="referencedAssemblySymbols"/> with the result.
/// The AssemblySymbols must correspond
/// to the AssemblyNames returned by AssemblyData.AssemblyReferences property. If reference is not
/// resolved, null reference should be returned in the corresponding item.
/// </summary>
/// <param name="assemblySymbol">The target AssemblySymbol instance.</param>
/// <param name="referencedAssemblySymbols">A list which will be filled in with
/// AssemblySymbols referenced by the input AssemblySymbol. The caller is expected to clear
/// the list before calling this method.
/// Implementer may not cache the list; the caller may mutate it.</param>
protected abstract void GetActualBoundReferencesUsedBy(TAssemblySymbol assemblySymbol, List<TAssemblySymbol?> referencedAssemblySymbols);
/// <summary>
/// Return collection of assemblies involved in canonical type resolution of
/// NoPia local types defined within target assembly. In other words, all
/// references used by previous compilation referencing the target assembly.
/// </summary>
protected abstract ImmutableArray<TAssemblySymbol> GetNoPiaResolutionAssemblies(TAssemblySymbol candidateAssembly);
/// <summary>
/// Assembly is /l-ed by compilation that is using it as a reference.
/// </summary>
protected abstract bool IsLinked(TAssemblySymbol candidateAssembly);
/// <summary>
/// Get Assembly used as COR library for the candidate.
/// </summary>
protected abstract TAssemblySymbol? GetCorLibrary(TAssemblySymbol candidateAssembly);
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using MethodAttributes = System.Reflection.MethodAttributes;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class TypeHelpers
{
internal const BindingFlags MemberBindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
internal static void AppendTypeMembers(
this Type type,
ArrayBuilder<MemberAndDeclarationInfo> includedMembers,
Predicate<MemberInfo> predicate,
Type declaredType,
DkmClrAppDomain appDomain,
bool includeInherited,
bool hideNonPublic,
bool isProxyType,
bool includeCompilerGenerated,
bool supportsFavorites,
DkmClrObjectFavoritesInfo favoritesInfo)
{
Debug.Assert(!type.IsInterface);
var memberLocation = DeclarationInfo.FromSubTypeOfDeclaredType;
var previousDeclarationMap = includeInherited ? new Dictionary<string, DeclarationInfo>() : null;
int inheritanceLevel = 0;
while (!type.IsObject())
{
if (type.Equals(declaredType))
{
Debug.Assert(memberLocation == DeclarationInfo.FromSubTypeOfDeclaredType);
memberLocation = DeclarationInfo.FromDeclaredTypeOrBase;
}
// Get the state from DebuggerBrowsableAttributes for the members of the current type.
var browsableState = DkmClrType.Create(appDomain, type).GetDebuggerBrowsableAttributeState();
// Disable favorites if any of the members have a browsable state of RootHidden
if (supportsFavorites && browsableState != null)
{
foreach (var browsableStateValue in browsableState.Values)
{
if (browsableStateValue == DkmClrDebuggerBrowsableAttributeState.RootHidden)
{
supportsFavorites = false;
break;
}
}
}
// Get the favorites information if it is supported.
// NOTE: Using a Dictionary since Hashset is not available in .net 2.0
Dictionary<string, object> favoritesMemberNames = null;
if (supportsFavorites && favoritesInfo?.Favorites != null)
{
favoritesMemberNames = new Dictionary<string, object>(favoritesInfo.Favorites.Count);
foreach (var favorite in favoritesInfo.Favorites)
{
favoritesMemberNames.Add(favorite, null);
}
}
// Hide non-public members if hideNonPublic is specified (intended to reflect the
// DkmInspectionContext's DkmEvaluationFlags), and the type is from an assembly
// with no symbols.
var hideNonPublicBehavior = DeclarationInfo.None;
if (hideNonPublic)
{
var moduleInstance = appDomain.FindClrModuleInstance(type.Module.ModuleVersionId);
if (moduleInstance == null || moduleInstance.Module == null)
{
// Synthetic module or no symbols loaded.
hideNonPublicBehavior = DeclarationInfo.HideNonPublic;
}
}
foreach (var member in type.GetMembers(MemberBindingFlags))
{
var memberName = member.Name;
if (!includeCompilerGenerated && memberName.IsCompilerGenerated())
{
continue;
}
// The native EE shows proxy members regardless of accessibility if they have a
// DebuggerBrowsable attribute of any value. Match that behaviour here.
if (!isProxyType || browsableState == null || !browsableState.ContainsKey(memberName))
{
if (!predicate(member))
{
continue;
}
}
// This represents information about the immediately preceding (more derived)
// declaration with the same name as the current member.
var previousDeclaration = DeclarationInfo.None;
var memberNameAlreadySeen = false;
if (includeInherited)
{
memberNameAlreadySeen = previousDeclarationMap.TryGetValue(memberName, out previousDeclaration);
if (memberNameAlreadySeen)
{
// There was a name conflict, so we'll need to include the declaring
// type of the member to disambiguate.
previousDeclaration |= DeclarationInfo.IncludeTypeInMemberName;
}
// Update previous member with name hiding (casting) and declared location information for next time.
previousDeclarationMap[memberName] =
(previousDeclaration & ~(DeclarationInfo.RequiresExplicitCast |
DeclarationInfo.FromSubTypeOfDeclaredType)) |
member.AccessingBaseMemberWithSameNameRequiresExplicitCast() |
memberLocation;
}
Debug.Assert(memberNameAlreadySeen != (previousDeclaration == DeclarationInfo.None));
// Decide whether to include this member in the list of members to display.
if (!memberNameAlreadySeen || previousDeclaration.IsSet(DeclarationInfo.RequiresExplicitCast))
{
DkmClrDebuggerBrowsableAttributeState? browsableStateValue = null;
if (browsableState != null)
{
DkmClrDebuggerBrowsableAttributeState value;
if (browsableState.TryGetValue(memberName, out value))
{
browsableStateValue = value;
}
}
if (memberLocation.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the current type is a sub-type of the declared type, then
// we always need to insert a cast to access the member
previousDeclaration |= DeclarationInfo.RequiresExplicitCast;
}
else if (previousDeclaration.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the immediately preceding member (less derived) was
// declared on a sub-type of the declared type, then we'll
// ignore the casting bit. Accessing a member through the
// declared type is the same as casting to that type, so
// the cast would be redundant.
previousDeclaration &= ~DeclarationInfo.RequiresExplicitCast;
}
previousDeclaration |= hideNonPublicBehavior;
includedMembers.Add(
new MemberAndDeclarationInfo(
member,
browsableStateValue,
previousDeclaration,
inheritanceLevel,
canFavorite: supportsFavorites,
isFavorite: favoritesMemberNames?.ContainsKey(memberName) == true));
}
}
if (!includeInherited)
{
break;
}
type = type.BaseType;
inheritanceLevel++;
}
includedMembers.Sort(MemberAndDeclarationInfo.Comparer);
}
private static DeclarationInfo AccessingBaseMemberWithSameNameRequiresExplicitCast(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return DeclarationInfo.RequiresExplicitCast;
case MemberTypes.Property:
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if ((getMethod != null) &&
(!getMethod.IsVirtual || ((getMethod.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot)))
{
return DeclarationInfo.RequiresExplicitCast;
}
return DeclarationInfo.None;
default:
throw ExceptionUtilities.UnexpectedValue(member.MemberType);
}
}
internal static bool IsVisibleMember(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return GetNonIndexerGetMethod((PropertyInfo)member) != null;
}
return false;
}
/// <summary>
/// Returns true if the member is public or protected.
/// </summary>
internal static bool IsPublic(this MemberInfo member)
{
// Matches native EE which includes protected members.
switch (member.MemberType)
{
case MemberTypes.Field:
{
var field = (FieldInfo)member;
var attributes = field.Attributes;
return ((attributes & System.Reflection.FieldAttributes.Public) == System.Reflection.FieldAttributes.Public) ||
((attributes & System.Reflection.FieldAttributes.Family) == System.Reflection.FieldAttributes.Family);
}
case MemberTypes.Property:
{
// Native EE uses the accessibility of the property rather than getter
// so "public object P { private get; set; }" is treated as public.
// Instead, we drop properties if the getter is inaccessible.
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if (getMethod == null)
{
return false;
}
var attributes = getMethod.Attributes;
return ((attributes & System.Reflection.MethodAttributes.Public) == System.Reflection.MethodAttributes.Public) ||
((attributes & System.Reflection.MethodAttributes.Family) == System.Reflection.MethodAttributes.Family);
}
default:
return false;
}
}
private static MethodInfo GetNonIndexerGetMethod(PropertyInfo property)
{
return (property.GetIndexParameters().Length == 0) ?
property.GetGetMethod(nonPublic: true) :
null;
}
internal static bool IsBoolean(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Boolean;
}
internal static bool IsCharacter(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Char;
}
internal static bool IsDecimal(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Decimal;
}
internal static bool IsDateTime(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.DateTime;
}
internal static bool IsObject(this Type type)
{
bool result = type.IsClass && (type.BaseType == null) && !type.IsPointer;
Debug.Assert(result == type.IsMscorlibType("System", "Object"));
return result;
}
internal static bool IsValueType(this Type type)
{
return type.IsMscorlibType("System", "ValueType");
}
internal static bool IsString(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.String;
}
internal static bool IsVoid(this Type type)
{
return type.IsMscorlibType("System", "Void") && !type.IsGenericType;
}
internal static bool IsIEnumerable(this Type type)
{
return type.IsMscorlibType("System.Collections", "IEnumerable");
}
internal static bool IsIntPtr(this Type type)
=> type.IsMscorlibType("System", "IntPtr");
internal static bool IsUIntPtr(this Type type)
=> type.IsMscorlibType("System", "UIntPtr");
internal static bool IsIEnumerableOfT(this Type type)
{
return type.IsMscorlibType("System.Collections.Generic", "IEnumerable`1");
}
internal static bool IsTypeVariables(this Type type)
{
return type.IsType(null, "<>c__TypeVariables");
}
internal static bool IsComObject(this Type type)
{
return type.IsType("System", "__ComObject");
}
internal static bool IsDynamicProperty(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicProperty");
}
internal static bool IsDynamicDebugViewEmptyException(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicDebugViewEmptyException");
}
internal static bool IsIDynamicMetaObjectProvider(this Type type)
{
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsType("System.Dynamic", "IDynamicMetaObjectProvider"))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns type argument if the type is
/// Nullable<T>, otherwise null.
/// </summary>
internal static Type GetNullableTypeArgument(this Type type)
{
if (type.IsMscorlibType("System", "Nullable`1"))
{
var typeArgs = type.GetGenericArguments();
if (typeArgs.Length == 1)
{
return typeArgs[0];
}
}
return null;
}
internal static bool IsNullable(this Type type)
{
return type.GetNullableTypeArgument() != null;
}
internal static DkmClrValue GetFieldValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Field, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetPropertyValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Property, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, Type nullableTypeArg, DkmInspectionContext inspectionContext)
{
var valueType = value.Type.GetLmrType();
if (valueType.Equals(nullableTypeArg))
{
return value;
}
return value.GetNullableValue(inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(value.Type.GetLmrType().IsNullable());
var hasValue = value.GetFieldValue(InternalWellKnownMemberNames.NullableHasValue, inspectionContext);
if (object.Equals(hasValue.HostObjectValue, false))
{
return null;
}
return value.GetFieldValue(InternalWellKnownMemberNames.NullableValue, inspectionContext);
}
internal const int TupleFieldRestPosition = 8;
private const string TupleTypeNamePrefix = "ValueTuple`";
private const string TupleFieldItemNamePrefix = "Item";
internal const string TupleFieldRestName = "Rest";
// See NamedTypeSymbol.IsTupleCompatible.
internal static bool IsTupleCompatible(this Type type, out int cardinality)
{
if (type.IsGenericType &&
AreNamesEqual(type.Namespace, "System") &&
type.Name.StartsWith(TupleTypeNamePrefix, StringComparison.Ordinal))
{
var typeArguments = type.GetGenericArguments();
int n = typeArguments.Length;
if ((n > 0) && (n <= TupleFieldRestPosition))
{
if (!AreNamesEqual(type.Name, TupleTypeNamePrefix + n))
{
cardinality = 0;
return false;
}
if (n < TupleFieldRestPosition)
{
cardinality = n;
return true;
}
var restType = typeArguments[n - 1];
int restCardinality;
if (restType.IsTupleCompatible(out restCardinality))
{
cardinality = n - 1 + restCardinality;
return true;
}
}
}
cardinality = 0;
return false;
}
// Returns cardinality if tuple type, otherwise 0.
internal static int GetTupleCardinalityIfAny(this Type type)
{
int cardinality;
type.IsTupleCompatible(out cardinality);
return cardinality;
}
internal static FieldInfo GetTupleField(this Type type, string name)
{
return type.GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
}
internal static string GetTupleFieldName(int index)
{
Debug.Assert(index >= 0);
return TupleFieldItemNamePrefix + (index + 1);
}
internal static bool TryGetTupleFieldValues(this DkmClrValue tuple, int cardinality, ArrayBuilder<string> values, DkmInspectionContext inspectionContext)
{
while (true)
{
var type = tuple.Type.GetLmrType();
int n = Math.Min(cardinality, TupleFieldRestPosition - 1);
for (int index = 0; index < n; index++)
{
var fieldName = GetTupleFieldName(index);
var fieldInfo = type.GetTupleField(fieldName);
if (fieldInfo == null)
{
return false;
}
var value = tuple.GetFieldValue(fieldName, inspectionContext);
var str = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
values.Add(str);
}
cardinality -= n;
if (cardinality == 0)
{
return true;
}
var restInfo = type.GetTupleField(TypeHelpers.TupleFieldRestName);
if (restInfo == null)
{
return false;
}
tuple = tuple.GetFieldValue(TupleFieldRestName, inspectionContext);
}
}
internal static Type GetBaseTypeOrNull(this Type underlyingType, DkmClrAppDomain appDomain, out DkmClrType type)
{
Debug.Assert((underlyingType.BaseType != null) || underlyingType.IsPointer || underlyingType.IsArray, "BaseType should only return null if the underlyingType is a pointer or array.");
underlyingType = underlyingType.BaseType;
type = (underlyingType != null) ? DkmClrType.Create(appDomain, underlyingType) : null;
return underlyingType;
}
/// <summary>
/// Get the first attribute from <see cref="DkmClrType.GetEvalAttributes()"/> (including inherited attributes)
/// that is of type T, as well as the type that it targeted.
/// </summary>
internal static bool TryGetEvalAttribute<T>(this DkmClrType type, out DkmClrType attributeTarget, out T evalAttribute)
where T : DkmClrEvalAttribute
{
attributeTarget = null;
evalAttribute = null;
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
evalAttribute = attribute as T;
if (evalAttribute != null)
{
attributeTarget = type;
return true;
}
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
return false;
}
/// <summary>
/// Returns the set of DebuggerBrowsableAttribute state for the
/// members of the type, indexed by member name, or null if there
/// are no DebuggerBrowsableAttributes on members of the type.
/// </summary>
private static Dictionary<string, DkmClrDebuggerBrowsableAttributeState> GetDebuggerBrowsableAttributeState(this DkmClrType type)
{
Dictionary<string, DkmClrDebuggerBrowsableAttributeState> result = null;
foreach (var attribute in type.GetEvalAttributes())
{
var browsableAttribute = attribute as DkmClrDebuggerBrowsableAttribute;
if (browsableAttribute == null)
{
continue;
}
if (result == null)
{
result = new Dictionary<string, DkmClrDebuggerBrowsableAttributeState>();
}
// There can be multiple same attributes for derived classes.
// Debugger provides attributes starting from derived classes and then up to base ones.
// We should use derived attributes if there is more than one instance.
if (!result.ContainsKey(browsableAttribute.TargetMember))
{
result.Add(browsableAttribute.TargetMember, browsableAttribute.State);
}
}
return result;
}
/// <summary>
/// Extracts information from the first <see cref="DebuggerDisplayAttribute"/> on the runtime type of <paramref name="value"/>, if there is one.
/// </summary>
internal static bool TryGetDebuggerDisplayInfo(this DkmClrValue value, out DebuggerDisplayInfo displayInfo)
{
displayInfo = null;
// The native EE does not consider DebuggerDisplayAttribute
// on null or error instances.
if (value.IsError() || value.IsNull)
{
return false;
}
var clrType = value.Type;
displayInfo = new DebuggerDisplayInfo(clrType);
DkmClrObjectFavoritesInfo favoritesInfo = clrType.GetFavorites();
if (favoritesInfo != null)
{
displayInfo = displayInfo.WithFavoritesInfo(favoritesInfo);
}
DkmClrType attributeTarget;
DkmClrDebuggerDisplayAttribute attribute;
if (clrType.TryGetEvalAttribute(out attributeTarget, out attribute)) // First, as in dev12.
{
displayInfo = displayInfo.WithDebuggerDisplayAttribute(attribute, attributeTarget);
}
return displayInfo.HasValues;
}
/// <summary>
/// Returns the array of <see cref="DkmCustomUIVisualizerInfo"/> objects of the type from its <see cref="DkmClrDebuggerVisualizerAttribute"/> attributes,
/// or null if the type has no [DebuggerVisualizer] attributes associated with it.
/// </summary>
internal static DkmCustomUIVisualizerInfo[] GetDebuggerCustomUIVisualizerInfo(this DkmClrType type)
{
var builder = ArrayBuilder<DkmCustomUIVisualizerInfo>.GetInstance();
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
var visualizerAttribute = attribute as DkmClrDebuggerVisualizerAttribute;
if (visualizerAttribute == null)
{
continue;
}
builder.Add(DkmCustomUIVisualizerInfo.Create((uint)builder.Count,
visualizerAttribute.VisualizerDescription,
visualizerAttribute.VisualizerDescription,
// ClrCustomVisualizerVSHost is a registry entry that specifies the CLSID of the
// IDebugCustomViewer class that will be instantiated to display the custom visualizer.
"ClrCustomVisualizerVSHost",
visualizerAttribute.UISideVisualizerTypeName,
visualizerAttribute.UISideVisualizerAssemblyName,
visualizerAttribute.UISideVisualizerAssemblyLocation,
visualizerAttribute.DebuggeeSideVisualizerTypeName,
visualizerAttribute.DebuggeeSideVisualizerAssemblyName));
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
var result = (builder.Count > 0) ? builder.ToArray() : null;
builder.Free();
return result;
}
internal static DkmClrType GetProxyType(this DkmClrType type)
{
// CONSIDER: If needed, we could probably compute a new DynamicAttribute for
// the proxy type based on the DynamicAttribute of the argument.
DkmClrType attributeTarget;
DkmClrDebuggerTypeProxyAttribute attribute;
if (type.TryGetEvalAttribute(out attributeTarget, out attribute))
{
var targetedType = attributeTarget.GetLmrType();
var proxyType = attribute.ProxyType;
var underlyingProxy = proxyType.GetLmrType();
if (underlyingProxy.IsGenericType && targetedType.IsGenericType)
{
var typeArgs = targetedType.GetGenericArguments();
// Drop the proxy type if the arity does not match.
if (typeArgs.Length != underlyingProxy.GetGenericArguments().Length)
{
return null;
}
// Substitute target type arguments for proxy type arguments.
var constructedProxy = underlyingProxy.Substitute(underlyingProxy, typeArgs);
proxyType = DkmClrType.Create(type.AppDomain, constructedProxy);
}
return proxyType;
}
return null;
}
/// <summary>
/// Substitute references to type parameters from 'typeDef'
/// with type arguments from 'typeArgs' in type 'type'.
/// </summary>
internal static Type Substitute(this Type type, Type typeDef, Type[] typeArgs)
{
Debug.Assert(typeDef.IsGenericTypeDefinition);
Debug.Assert(typeDef.GetGenericArguments().Length == typeArgs.Length);
if (type.IsGenericType)
{
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var t in type.GetGenericArguments())
{
builder.Add(t.Substitute(typeDef, typeArgs));
}
var typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition.MakeGenericType(builder.ToArrayAndFree());
}
else if (type.IsArray)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
var n = type.GetArrayRank();
return (n == 1) ? elementType.MakeArrayType() : elementType.MakeArrayType(n);
}
else if (type.IsPointer)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
return elementType.MakePointerType();
}
else if (type.IsGenericParameter)
{
if (type.DeclaringType.Equals(typeDef))
{
var ordinal = type.GenericParameterPosition;
return typeArgs[ordinal];
}
}
return type;
}
// Returns the IEnumerable interface implemented by the given type,
// preferring System.Collections.Generic.IEnumerable<T> over
// System.Collections.IEnumerable. If there are multiple implementations
// of IEnumerable<T> on base and derived types, the implementation on
// the most derived type is returned. If there are multiple implementations
// of IEnumerable<T> on the same type, it is undefined which is returned.
internal static Type GetIEnumerableImplementationIfAny(this Type type)
{
var t = type;
do
{
foreach (var @interface in t.GetInterfacesOnType())
{
if (@interface.IsIEnumerableOfT())
{
// Return the first implementation of IEnumerable<T>.
return @interface;
}
}
t = t.BaseType;
} while (t != null);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsIEnumerable())
{
return @interface;
}
}
return null;
}
internal static bool IsEmptyResultsViewException(this Type type)
{
return type.IsType("System.Linq", "SystemCore_EnumerableDebugViewEmptyException");
}
internal static bool IsOrInheritsFrom(this Type type, Type baseType)
{
Debug.Assert(type != null);
Debug.Assert(baseType != null);
Debug.Assert(!baseType.IsInterface);
if (type.IsInterface)
{
return false;
}
do
{
if (type.Equals(baseType))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
private static bool IsMscorlib(this Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0;
}
private static bool IsMscorlibType(this Type type, string @namespace, string name)
{
// Ignore IsMscorlib for now since type.Assembly returns
// System.Runtime.dll for some types in mscorlib.dll.
// TODO: Re-enable commented out check.
return type.IsType(@namespace, name) /*&& type.Assembly.IsMscorlib()*/;
}
internal static bool IsOrInheritsFrom(this Type type, string @namespace, string name)
{
do
{
if (type.IsType(@namespace, name))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
internal static bool IsType(this Type type, string @namespace, string name)
{
Debug.Assert((@namespace == null) || (@namespace.Length > 0)); // Type.Namespace is null not empty.
Debug.Assert(!string.IsNullOrEmpty(name));
return AreNamesEqual(type.Namespace, @namespace) &&
AreNamesEqual(type.Name, name);
}
private static bool AreNamesEqual(string nameA, string nameB)
{
return string.Equals(nameA, nameB, StringComparison.Ordinal);
}
internal static MemberInfo GetOriginalDefinition(this MemberInfo member)
{
var declaringType = member.DeclaringType;
if (!declaringType.IsGenericType)
{
return member;
}
var declaringTypeOriginalDefinition = declaringType.GetGenericTypeDefinition();
if (declaringType.Equals(declaringTypeOriginalDefinition))
{
return member;
}
foreach (var candidate in declaringTypeOriginalDefinition.GetMember(member.Name, MemberBindingFlags))
{
var memberType = candidate.MemberType;
if (memberType != member.MemberType)
continue;
switch (memberType)
{
case MemberTypes.Field:
return candidate;
case MemberTypes.Property:
Debug.Assert(((PropertyInfo)member).GetIndexParameters().Length == 0);
if (((PropertyInfo)candidate).GetIndexParameters().Length == 0)
{
return candidate;
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(memberType);
}
}
throw ExceptionUtilities.Unreachable;
}
internal static Type GetInterfaceListEntry(this Type interfaceType, Type declaration)
{
Debug.Assert(interfaceType.IsInterface);
if (!interfaceType.IsGenericType || !declaration.IsGenericType)
{
return interfaceType;
}
var index = Array.IndexOf(declaration.GetInterfacesOnType(), interfaceType);
Debug.Assert(index >= 0);
var result = declaration.GetGenericTypeDefinition().GetInterfacesOnType()[index];
Debug.Assert(interfaceType.GetGenericTypeDefinition().Equals(result.GetGenericTypeDefinition()));
return result;
}
internal static MemberAndDeclarationInfo GetMemberByName(this DkmClrType type, string name)
{
var members = type.GetLmrType().GetMember(name, TypeHelpers.MemberBindingFlags);
Debug.Assert(members.Length == 1);
return new MemberAndDeclarationInfo(members[0], browsableState: null, info: DeclarationInfo.None, inheritanceLevel: 0, canFavorite: false, isFavorite: false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using MethodAttributes = System.Reflection.MethodAttributes;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class TypeHelpers
{
internal const BindingFlags MemberBindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
internal static void AppendTypeMembers(
this Type type,
ArrayBuilder<MemberAndDeclarationInfo> includedMembers,
Predicate<MemberInfo> predicate,
Type declaredType,
DkmClrAppDomain appDomain,
bool includeInherited,
bool hideNonPublic,
bool isProxyType,
bool includeCompilerGenerated,
bool supportsFavorites,
DkmClrObjectFavoritesInfo favoritesInfo)
{
Debug.Assert(!type.IsInterface);
var memberLocation = DeclarationInfo.FromSubTypeOfDeclaredType;
var previousDeclarationMap = includeInherited ? new Dictionary<string, DeclarationInfo>() : null;
int inheritanceLevel = 0;
while (!type.IsObject())
{
if (type.Equals(declaredType))
{
Debug.Assert(memberLocation == DeclarationInfo.FromSubTypeOfDeclaredType);
memberLocation = DeclarationInfo.FromDeclaredTypeOrBase;
}
// Get the state from DebuggerBrowsableAttributes for the members of the current type.
var browsableState = DkmClrType.Create(appDomain, type).GetDebuggerBrowsableAttributeState();
// Disable favorites if any of the members have a browsable state of RootHidden
if (supportsFavorites && browsableState != null)
{
foreach (var browsableStateValue in browsableState.Values)
{
if (browsableStateValue == DkmClrDebuggerBrowsableAttributeState.RootHidden)
{
supportsFavorites = false;
break;
}
}
}
// Get the favorites information if it is supported.
// NOTE: Using a Dictionary since Hashset is not available in .net 2.0
Dictionary<string, object> favoritesMemberNames = null;
if (supportsFavorites && favoritesInfo?.Favorites != null)
{
favoritesMemberNames = new Dictionary<string, object>(favoritesInfo.Favorites.Count);
foreach (var favorite in favoritesInfo.Favorites)
{
favoritesMemberNames.Add(favorite, null);
}
}
// Hide non-public members if hideNonPublic is specified (intended to reflect the
// DkmInspectionContext's DkmEvaluationFlags), and the type is from an assembly
// with no symbols.
var hideNonPublicBehavior = DeclarationInfo.None;
if (hideNonPublic)
{
var moduleInstance = appDomain.FindClrModuleInstance(type.Module.ModuleVersionId);
if (moduleInstance == null || moduleInstance.Module == null)
{
// Synthetic module or no symbols loaded.
hideNonPublicBehavior = DeclarationInfo.HideNonPublic;
}
}
foreach (var member in type.GetMembers(MemberBindingFlags))
{
var memberName = member.Name;
if (!includeCompilerGenerated && memberName.IsCompilerGenerated())
{
continue;
}
// The native EE shows proxy members regardless of accessibility if they have a
// DebuggerBrowsable attribute of any value. Match that behaviour here.
if (!isProxyType || browsableState == null || !browsableState.ContainsKey(memberName))
{
if (!predicate(member))
{
continue;
}
}
// This represents information about the immediately preceding (more derived)
// declaration with the same name as the current member.
var previousDeclaration = DeclarationInfo.None;
var memberNameAlreadySeen = false;
if (includeInherited)
{
memberNameAlreadySeen = previousDeclarationMap.TryGetValue(memberName, out previousDeclaration);
if (memberNameAlreadySeen)
{
// There was a name conflict, so we'll need to include the declaring
// type of the member to disambiguate.
previousDeclaration |= DeclarationInfo.IncludeTypeInMemberName;
}
// Update previous member with name hiding (casting) and declared location information for next time.
previousDeclarationMap[memberName] =
(previousDeclaration & ~(DeclarationInfo.RequiresExplicitCast |
DeclarationInfo.FromSubTypeOfDeclaredType)) |
member.AccessingBaseMemberWithSameNameRequiresExplicitCast() |
memberLocation;
}
Debug.Assert(memberNameAlreadySeen != (previousDeclaration == DeclarationInfo.None));
// Decide whether to include this member in the list of members to display.
if (!memberNameAlreadySeen || previousDeclaration.IsSet(DeclarationInfo.RequiresExplicitCast))
{
DkmClrDebuggerBrowsableAttributeState? browsableStateValue = null;
if (browsableState != null)
{
DkmClrDebuggerBrowsableAttributeState value;
if (browsableState.TryGetValue(memberName, out value))
{
browsableStateValue = value;
}
}
if (memberLocation.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the current type is a sub-type of the declared type, then
// we always need to insert a cast to access the member
previousDeclaration |= DeclarationInfo.RequiresExplicitCast;
}
else if (previousDeclaration.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the immediately preceding member (less derived) was
// declared on a sub-type of the declared type, then we'll
// ignore the casting bit. Accessing a member through the
// declared type is the same as casting to that type, so
// the cast would be redundant.
previousDeclaration &= ~DeclarationInfo.RequiresExplicitCast;
}
previousDeclaration |= hideNonPublicBehavior;
includedMembers.Add(
new MemberAndDeclarationInfo(
member,
browsableStateValue,
previousDeclaration,
inheritanceLevel,
canFavorite: supportsFavorites,
isFavorite: favoritesMemberNames?.ContainsKey(memberName) == true));
}
}
if (!includeInherited)
{
break;
}
type = type.BaseType;
inheritanceLevel++;
}
includedMembers.Sort(MemberAndDeclarationInfo.Comparer);
}
private static DeclarationInfo AccessingBaseMemberWithSameNameRequiresExplicitCast(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return DeclarationInfo.RequiresExplicitCast;
case MemberTypes.Property:
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if ((getMethod != null) &&
(!getMethod.IsVirtual || ((getMethod.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot)))
{
return DeclarationInfo.RequiresExplicitCast;
}
return DeclarationInfo.None;
default:
throw ExceptionUtilities.UnexpectedValue(member.MemberType);
}
}
internal static bool IsVisibleMember(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return GetNonIndexerGetMethod((PropertyInfo)member) != null;
}
return false;
}
/// <summary>
/// Returns true if the member is public or protected.
/// </summary>
internal static bool IsPublic(this MemberInfo member)
{
// Matches native EE which includes protected members.
switch (member.MemberType)
{
case MemberTypes.Field:
{
var field = (FieldInfo)member;
var attributes = field.Attributes;
return ((attributes & System.Reflection.FieldAttributes.Public) == System.Reflection.FieldAttributes.Public) ||
((attributes & System.Reflection.FieldAttributes.Family) == System.Reflection.FieldAttributes.Family);
}
case MemberTypes.Property:
{
// Native EE uses the accessibility of the property rather than getter
// so "public object P { private get; set; }" is treated as public.
// Instead, we drop properties if the getter is inaccessible.
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if (getMethod == null)
{
return false;
}
var attributes = getMethod.Attributes;
return ((attributes & System.Reflection.MethodAttributes.Public) == System.Reflection.MethodAttributes.Public) ||
((attributes & System.Reflection.MethodAttributes.Family) == System.Reflection.MethodAttributes.Family);
}
default:
return false;
}
}
private static MethodInfo GetNonIndexerGetMethod(PropertyInfo property)
{
return (property.GetIndexParameters().Length == 0) ?
property.GetGetMethod(nonPublic: true) :
null;
}
internal static bool IsBoolean(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Boolean;
}
internal static bool IsCharacter(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Char;
}
internal static bool IsDecimal(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Decimal;
}
internal static bool IsDateTime(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.DateTime;
}
internal static bool IsObject(this Type type)
{
bool result = type.IsClass && (type.BaseType == null) && !type.IsPointer;
Debug.Assert(result == type.IsMscorlibType("System", "Object"));
return result;
}
internal static bool IsValueType(this Type type)
{
return type.IsMscorlibType("System", "ValueType");
}
internal static bool IsString(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.String;
}
internal static bool IsVoid(this Type type)
{
return type.IsMscorlibType("System", "Void") && !type.IsGenericType;
}
internal static bool IsIEnumerable(this Type type)
{
return type.IsMscorlibType("System.Collections", "IEnumerable");
}
internal static bool IsIntPtr(this Type type)
=> type.IsMscorlibType("System", "IntPtr");
internal static bool IsUIntPtr(this Type type)
=> type.IsMscorlibType("System", "UIntPtr");
internal static bool IsIEnumerableOfT(this Type type)
{
return type.IsMscorlibType("System.Collections.Generic", "IEnumerable`1");
}
internal static bool IsTypeVariables(this Type type)
{
return type.IsType(null, "<>c__TypeVariables");
}
internal static bool IsComObject(this Type type)
{
return type.IsType("System", "__ComObject");
}
internal static bool IsDynamicProperty(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicProperty");
}
internal static bool IsDynamicDebugViewEmptyException(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicDebugViewEmptyException");
}
internal static bool IsIDynamicMetaObjectProvider(this Type type)
{
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsType("System.Dynamic", "IDynamicMetaObjectProvider"))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns type argument if the type is
/// Nullable<T>, otherwise null.
/// </summary>
internal static Type GetNullableTypeArgument(this Type type)
{
if (type.IsMscorlibType("System", "Nullable`1"))
{
var typeArgs = type.GetGenericArguments();
if (typeArgs.Length == 1)
{
return typeArgs[0];
}
}
return null;
}
internal static bool IsNullable(this Type type)
{
return type.GetNullableTypeArgument() != null;
}
internal static DkmClrValue GetFieldValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Field, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetPropertyValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Property, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, Type nullableTypeArg, DkmInspectionContext inspectionContext)
{
var valueType = value.Type.GetLmrType();
if (valueType.Equals(nullableTypeArg))
{
return value;
}
return value.GetNullableValue(inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(value.Type.GetLmrType().IsNullable());
var hasValue = value.GetFieldValue(InternalWellKnownMemberNames.NullableHasValue, inspectionContext);
if (object.Equals(hasValue.HostObjectValue, false))
{
return null;
}
return value.GetFieldValue(InternalWellKnownMemberNames.NullableValue, inspectionContext);
}
internal const int TupleFieldRestPosition = 8;
private const string TupleTypeNamePrefix = "ValueTuple`";
private const string TupleFieldItemNamePrefix = "Item";
internal const string TupleFieldRestName = "Rest";
// See NamedTypeSymbol.IsTupleCompatible.
internal static bool IsTupleCompatible(this Type type, out int cardinality)
{
if (type.IsGenericType &&
AreNamesEqual(type.Namespace, "System") &&
type.Name.StartsWith(TupleTypeNamePrefix, StringComparison.Ordinal))
{
var typeArguments = type.GetGenericArguments();
int n = typeArguments.Length;
if ((n > 0) && (n <= TupleFieldRestPosition))
{
if (!AreNamesEqual(type.Name, TupleTypeNamePrefix + n))
{
cardinality = 0;
return false;
}
if (n < TupleFieldRestPosition)
{
cardinality = n;
return true;
}
var restType = typeArguments[n - 1];
int restCardinality;
if (restType.IsTupleCompatible(out restCardinality))
{
cardinality = n - 1 + restCardinality;
return true;
}
}
}
cardinality = 0;
return false;
}
// Returns cardinality if tuple type, otherwise 0.
internal static int GetTupleCardinalityIfAny(this Type type)
{
int cardinality;
type.IsTupleCompatible(out cardinality);
return cardinality;
}
internal static FieldInfo GetTupleField(this Type type, string name)
{
return type.GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
}
internal static string GetTupleFieldName(int index)
{
Debug.Assert(index >= 0);
return TupleFieldItemNamePrefix + (index + 1);
}
internal static bool TryGetTupleFieldValues(this DkmClrValue tuple, int cardinality, ArrayBuilder<string> values, DkmInspectionContext inspectionContext)
{
while (true)
{
var type = tuple.Type.GetLmrType();
int n = Math.Min(cardinality, TupleFieldRestPosition - 1);
for (int index = 0; index < n; index++)
{
var fieldName = GetTupleFieldName(index);
var fieldInfo = type.GetTupleField(fieldName);
if (fieldInfo == null)
{
return false;
}
var value = tuple.GetFieldValue(fieldName, inspectionContext);
var str = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
values.Add(str);
}
cardinality -= n;
if (cardinality == 0)
{
return true;
}
var restInfo = type.GetTupleField(TypeHelpers.TupleFieldRestName);
if (restInfo == null)
{
return false;
}
tuple = tuple.GetFieldValue(TupleFieldRestName, inspectionContext);
}
}
internal static Type GetBaseTypeOrNull(this Type underlyingType, DkmClrAppDomain appDomain, out DkmClrType type)
{
Debug.Assert((underlyingType.BaseType != null) || underlyingType.IsPointer || underlyingType.IsArray, "BaseType should only return null if the underlyingType is a pointer or array.");
underlyingType = underlyingType.BaseType;
type = (underlyingType != null) ? DkmClrType.Create(appDomain, underlyingType) : null;
return underlyingType;
}
/// <summary>
/// Get the first attribute from <see cref="DkmClrType.GetEvalAttributes()"/> (including inherited attributes)
/// that is of type T, as well as the type that it targeted.
/// </summary>
internal static bool TryGetEvalAttribute<T>(this DkmClrType type, out DkmClrType attributeTarget, out T evalAttribute)
where T : DkmClrEvalAttribute
{
attributeTarget = null;
evalAttribute = null;
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
evalAttribute = attribute as T;
if (evalAttribute != null)
{
attributeTarget = type;
return true;
}
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
return false;
}
/// <summary>
/// Returns the set of DebuggerBrowsableAttribute state for the
/// members of the type, indexed by member name, or null if there
/// are no DebuggerBrowsableAttributes on members of the type.
/// </summary>
private static Dictionary<string, DkmClrDebuggerBrowsableAttributeState> GetDebuggerBrowsableAttributeState(this DkmClrType type)
{
Dictionary<string, DkmClrDebuggerBrowsableAttributeState> result = null;
foreach (var attribute in type.GetEvalAttributes())
{
var browsableAttribute = attribute as DkmClrDebuggerBrowsableAttribute;
if (browsableAttribute == null)
{
continue;
}
if (result == null)
{
result = new Dictionary<string, DkmClrDebuggerBrowsableAttributeState>();
}
// There can be multiple same attributes for derived classes.
// Debugger provides attributes starting from derived classes and then up to base ones.
// We should use derived attributes if there is more than one instance.
if (!result.ContainsKey(browsableAttribute.TargetMember))
{
result.Add(browsableAttribute.TargetMember, browsableAttribute.State);
}
}
return result;
}
/// <summary>
/// Extracts information from the first <see cref="DebuggerDisplayAttribute"/> on the runtime type of <paramref name="value"/>, if there is one.
/// </summary>
internal static bool TryGetDebuggerDisplayInfo(this DkmClrValue value, out DebuggerDisplayInfo displayInfo)
{
displayInfo = null;
// The native EE does not consider DebuggerDisplayAttribute
// on null or error instances.
if (value.IsError() || value.IsNull)
{
return false;
}
var clrType = value.Type;
displayInfo = new DebuggerDisplayInfo(clrType);
DkmClrObjectFavoritesInfo favoritesInfo = clrType.GetFavorites();
if (favoritesInfo != null)
{
displayInfo = displayInfo.WithFavoritesInfo(favoritesInfo);
}
DkmClrType attributeTarget;
DkmClrDebuggerDisplayAttribute attribute;
if (clrType.TryGetEvalAttribute(out attributeTarget, out attribute)) // First, as in dev12.
{
displayInfo = displayInfo.WithDebuggerDisplayAttribute(attribute, attributeTarget);
}
return displayInfo.HasValues;
}
/// <summary>
/// Returns the array of <see cref="DkmCustomUIVisualizerInfo"/> objects of the type from its <see cref="DkmClrDebuggerVisualizerAttribute"/> attributes,
/// or null if the type has no [DebuggerVisualizer] attributes associated with it.
/// </summary>
internal static DkmCustomUIVisualizerInfo[] GetDebuggerCustomUIVisualizerInfo(this DkmClrType type)
{
var builder = ArrayBuilder<DkmCustomUIVisualizerInfo>.GetInstance();
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
var visualizerAttribute = attribute as DkmClrDebuggerVisualizerAttribute;
if (visualizerAttribute == null)
{
continue;
}
builder.Add(DkmCustomUIVisualizerInfo.Create((uint)builder.Count,
visualizerAttribute.VisualizerDescription,
visualizerAttribute.VisualizerDescription,
// ClrCustomVisualizerVSHost is a registry entry that specifies the CLSID of the
// IDebugCustomViewer class that will be instantiated to display the custom visualizer.
"ClrCustomVisualizerVSHost",
visualizerAttribute.UISideVisualizerTypeName,
visualizerAttribute.UISideVisualizerAssemblyName,
visualizerAttribute.UISideVisualizerAssemblyLocation,
visualizerAttribute.DebuggeeSideVisualizerTypeName,
visualizerAttribute.DebuggeeSideVisualizerAssemblyName));
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
var result = (builder.Count > 0) ? builder.ToArray() : null;
builder.Free();
return result;
}
internal static DkmClrType GetProxyType(this DkmClrType type)
{
// CONSIDER: If needed, we could probably compute a new DynamicAttribute for
// the proxy type based on the DynamicAttribute of the argument.
DkmClrType attributeTarget;
DkmClrDebuggerTypeProxyAttribute attribute;
if (type.TryGetEvalAttribute(out attributeTarget, out attribute))
{
var targetedType = attributeTarget.GetLmrType();
var proxyType = attribute.ProxyType;
var underlyingProxy = proxyType.GetLmrType();
if (underlyingProxy.IsGenericType && targetedType.IsGenericType)
{
var typeArgs = targetedType.GetGenericArguments();
// Drop the proxy type if the arity does not match.
if (typeArgs.Length != underlyingProxy.GetGenericArguments().Length)
{
return null;
}
// Substitute target type arguments for proxy type arguments.
var constructedProxy = underlyingProxy.Substitute(underlyingProxy, typeArgs);
proxyType = DkmClrType.Create(type.AppDomain, constructedProxy);
}
return proxyType;
}
return null;
}
/// <summary>
/// Substitute references to type parameters from 'typeDef'
/// with type arguments from 'typeArgs' in type 'type'.
/// </summary>
internal static Type Substitute(this Type type, Type typeDef, Type[] typeArgs)
{
Debug.Assert(typeDef.IsGenericTypeDefinition);
Debug.Assert(typeDef.GetGenericArguments().Length == typeArgs.Length);
if (type.IsGenericType)
{
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var t in type.GetGenericArguments())
{
builder.Add(t.Substitute(typeDef, typeArgs));
}
var typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition.MakeGenericType(builder.ToArrayAndFree());
}
else if (type.IsArray)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
var n = type.GetArrayRank();
return (n == 1) ? elementType.MakeArrayType() : elementType.MakeArrayType(n);
}
else if (type.IsPointer)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
return elementType.MakePointerType();
}
else if (type.IsGenericParameter)
{
if (type.DeclaringType.Equals(typeDef))
{
var ordinal = type.GenericParameterPosition;
return typeArgs[ordinal];
}
}
return type;
}
// Returns the IEnumerable interface implemented by the given type,
// preferring System.Collections.Generic.IEnumerable<T> over
// System.Collections.IEnumerable. If there are multiple implementations
// of IEnumerable<T> on base and derived types, the implementation on
// the most derived type is returned. If there are multiple implementations
// of IEnumerable<T> on the same type, it is undefined which is returned.
internal static Type GetIEnumerableImplementationIfAny(this Type type)
{
var t = type;
do
{
foreach (var @interface in t.GetInterfacesOnType())
{
if (@interface.IsIEnumerableOfT())
{
// Return the first implementation of IEnumerable<T>.
return @interface;
}
}
t = t.BaseType;
} while (t != null);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsIEnumerable())
{
return @interface;
}
}
return null;
}
internal static bool IsEmptyResultsViewException(this Type type)
{
return type.IsType("System.Linq", "SystemCore_EnumerableDebugViewEmptyException");
}
internal static bool IsOrInheritsFrom(this Type type, Type baseType)
{
Debug.Assert(type != null);
Debug.Assert(baseType != null);
Debug.Assert(!baseType.IsInterface);
if (type.IsInterface)
{
return false;
}
do
{
if (type.Equals(baseType))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
private static bool IsMscorlib(this Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0;
}
private static bool IsMscorlibType(this Type type, string @namespace, string name)
{
// Ignore IsMscorlib for now since type.Assembly returns
// System.Runtime.dll for some types in mscorlib.dll.
// TODO: Re-enable commented out check.
return type.IsType(@namespace, name) /*&& type.Assembly.IsMscorlib()*/;
}
internal static bool IsOrInheritsFrom(this Type type, string @namespace, string name)
{
do
{
if (type.IsType(@namespace, name))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
internal static bool IsType(this Type type, string @namespace, string name)
{
Debug.Assert((@namespace == null) || (@namespace.Length > 0)); // Type.Namespace is null not empty.
Debug.Assert(!string.IsNullOrEmpty(name));
return AreNamesEqual(type.Namespace, @namespace) &&
AreNamesEqual(type.Name, name);
}
private static bool AreNamesEqual(string nameA, string nameB)
{
return string.Equals(nameA, nameB, StringComparison.Ordinal);
}
internal static MemberInfo GetOriginalDefinition(this MemberInfo member)
{
var declaringType = member.DeclaringType;
if (!declaringType.IsGenericType)
{
return member;
}
var declaringTypeOriginalDefinition = declaringType.GetGenericTypeDefinition();
if (declaringType.Equals(declaringTypeOriginalDefinition))
{
return member;
}
foreach (var candidate in declaringTypeOriginalDefinition.GetMember(member.Name, MemberBindingFlags))
{
var memberType = candidate.MemberType;
if (memberType != member.MemberType)
continue;
switch (memberType)
{
case MemberTypes.Field:
return candidate;
case MemberTypes.Property:
Debug.Assert(((PropertyInfo)member).GetIndexParameters().Length == 0);
if (((PropertyInfo)candidate).GetIndexParameters().Length == 0)
{
return candidate;
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(memberType);
}
}
throw ExceptionUtilities.Unreachable;
}
internal static Type GetInterfaceListEntry(this Type interfaceType, Type declaration)
{
Debug.Assert(interfaceType.IsInterface);
if (!interfaceType.IsGenericType || !declaration.IsGenericType)
{
return interfaceType;
}
var index = Array.IndexOf(declaration.GetInterfacesOnType(), interfaceType);
Debug.Assert(index >= 0);
var result = declaration.GetGenericTypeDefinition().GetInterfacesOnType()[index];
Debug.Assert(interfaceType.GetGenericTypeDefinition().Equals(result.GetGenericTypeDefinition()));
return result;
}
internal static MemberAndDeclarationInfo GetMemberByName(this DkmClrType type, string name)
{
var members = type.GetLmrType().GetMember(name, TypeHelpers.MemberBindingFlags);
Debug.Assert(members.Length == 1);
return new MemberAndDeclarationInfo(members[0], browsableState: null, info: DeclarationInfo.None, inheritanceLevel: 0, canFavorite: false, isFavorite: false);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/Symbols/Attributes/CommonTypeWellKnownAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on a type.
/// </summary>
internal class CommonTypeWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget
{
#region SpecialNameAttribute
private bool _hasSpecialNameAttribute;
public bool HasSpecialNameAttribute
{
get
{
VerifySealed(expected: true);
return _hasSpecialNameAttribute;
}
set
{
VerifySealed(expected: false);
_hasSpecialNameAttribute = value;
SetDataStored();
}
}
#endregion
#region SerializableAttribute
private bool _hasSerializableAttribute;
public bool HasSerializableAttribute
{
get
{
VerifySealed(expected: true);
return _hasSerializableAttribute;
}
set
{
VerifySealed(expected: false);
_hasSerializableAttribute = value;
SetDataStored();
}
}
#endregion
#region DefaultMemberAttribute
private bool _hasDefaultMemberAttribute;
public bool HasDefaultMemberAttribute
{
get
{
VerifySealed(expected: true);
return _hasDefaultMemberAttribute;
}
set
{
VerifySealed(expected: false);
_hasDefaultMemberAttribute = value;
SetDataStored();
}
}
#endregion
#region SuppressUnmanagedCodeSecurityAttribute
private bool _hasSuppressUnmanagedCodeSecurityAttribute;
public bool HasSuppressUnmanagedCodeSecurityAttribute
{
get
{
VerifySealed(expected: true);
return _hasSuppressUnmanagedCodeSecurityAttribute;
}
set
{
VerifySealed(expected: false);
_hasSuppressUnmanagedCodeSecurityAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
internal bool HasDeclarativeSecurity
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute;
}
}
/// <summary>
/// Returns data decoded from security attributes or null if there are no security attributes.
/// </summary>
public SecurityWellKnownAttributeData SecurityInformation
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData;
}
}
#endregion
#region WindowsRuntimeImportAttribute
private bool _hasWindowsRuntimeImportAttribute;
public bool HasWindowsRuntimeImportAttribute
{
get
{
VerifySealed(expected: true);
return _hasWindowsRuntimeImportAttribute;
}
set
{
VerifySealed(expected: false);
_hasWindowsRuntimeImportAttribute = value;
SetDataStored();
}
}
#endregion
#region GuidAttribute
// Decoded guid string from GuidAttribute
private string _guidString;
public string GuidString
{
get
{
VerifySealed(expected: true);
return _guidString;
}
set
{
VerifySealed(expected: false);
Debug.Assert(value != null);
_guidString = value;
SetDataStored();
}
}
#endregion
#region StructLayoutAttribute
private TypeLayout _layout;
private CharSet _charSet;
// StructLayoutAttribute
public void SetStructLayout(TypeLayout layout, CharSet charSet)
{
VerifySealed(expected: false);
Debug.Assert(charSet == CharSet.Ansi || charSet == CharSet.Unicode || charSet == Cci.Constants.CharSet_Auto);
_layout = layout;
_charSet = charSet;
SetDataStored();
}
public bool HasStructLayoutAttribute
{
get
{
VerifySealed(expected: true);
// charSet is non-zero iff it was set by SetStructLayout called from StructLayoutAttribute decoder
return _charSet != 0;
}
}
public TypeLayout Layout
{
get
{
VerifySealed(expected: true);
Debug.Assert(HasStructLayoutAttribute);
return _layout;
}
}
public CharSet MarshallingCharSet
{
get
{
VerifySealed(expected: true);
Debug.Assert(HasStructLayoutAttribute);
return _charSet;
}
}
#endregion
#region SecurityCriticalAttribute and SecuritySafeCriticalAttribute
private bool _hasSecurityCriticalAttributes;
public bool HasSecurityCriticalAttributes
{
get
{
VerifySealed(expected: true);
return _hasSecurityCriticalAttributes;
}
set
{
VerifySealed(expected: false);
_hasSecurityCriticalAttributes = value;
SetDataStored();
}
}
#endregion
#region ExcludeFromCodeCoverageAttribute
private bool _hasExcludeFromCodeCoverageAttribute;
public bool HasExcludeFromCodeCoverageAttribute
{
get
{
VerifySealed(expected: true);
return _hasExcludeFromCodeCoverageAttribute;
}
set
{
VerifySealed(expected: false);
_hasExcludeFromCodeCoverageAttribute = value;
SetDataStored();
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on a type.
/// </summary>
internal class CommonTypeWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget
{
#region SpecialNameAttribute
private bool _hasSpecialNameAttribute;
public bool HasSpecialNameAttribute
{
get
{
VerifySealed(expected: true);
return _hasSpecialNameAttribute;
}
set
{
VerifySealed(expected: false);
_hasSpecialNameAttribute = value;
SetDataStored();
}
}
#endregion
#region SerializableAttribute
private bool _hasSerializableAttribute;
public bool HasSerializableAttribute
{
get
{
VerifySealed(expected: true);
return _hasSerializableAttribute;
}
set
{
VerifySealed(expected: false);
_hasSerializableAttribute = value;
SetDataStored();
}
}
#endregion
#region DefaultMemberAttribute
private bool _hasDefaultMemberAttribute;
public bool HasDefaultMemberAttribute
{
get
{
VerifySealed(expected: true);
return _hasDefaultMemberAttribute;
}
set
{
VerifySealed(expected: false);
_hasDefaultMemberAttribute = value;
SetDataStored();
}
}
#endregion
#region SuppressUnmanagedCodeSecurityAttribute
private bool _hasSuppressUnmanagedCodeSecurityAttribute;
public bool HasSuppressUnmanagedCodeSecurityAttribute
{
get
{
VerifySealed(expected: true);
return _hasSuppressUnmanagedCodeSecurityAttribute;
}
set
{
VerifySealed(expected: false);
_hasSuppressUnmanagedCodeSecurityAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
internal bool HasDeclarativeSecurity
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute;
}
}
/// <summary>
/// Returns data decoded from security attributes or null if there are no security attributes.
/// </summary>
public SecurityWellKnownAttributeData SecurityInformation
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData;
}
}
#endregion
#region WindowsRuntimeImportAttribute
private bool _hasWindowsRuntimeImportAttribute;
public bool HasWindowsRuntimeImportAttribute
{
get
{
VerifySealed(expected: true);
return _hasWindowsRuntimeImportAttribute;
}
set
{
VerifySealed(expected: false);
_hasWindowsRuntimeImportAttribute = value;
SetDataStored();
}
}
#endregion
#region GuidAttribute
// Decoded guid string from GuidAttribute
private string _guidString;
public string GuidString
{
get
{
VerifySealed(expected: true);
return _guidString;
}
set
{
VerifySealed(expected: false);
Debug.Assert(value != null);
_guidString = value;
SetDataStored();
}
}
#endregion
#region StructLayoutAttribute
private TypeLayout _layout;
private CharSet _charSet;
// StructLayoutAttribute
public void SetStructLayout(TypeLayout layout, CharSet charSet)
{
VerifySealed(expected: false);
Debug.Assert(charSet == CharSet.Ansi || charSet == CharSet.Unicode || charSet == Cci.Constants.CharSet_Auto);
_layout = layout;
_charSet = charSet;
SetDataStored();
}
public bool HasStructLayoutAttribute
{
get
{
VerifySealed(expected: true);
// charSet is non-zero iff it was set by SetStructLayout called from StructLayoutAttribute decoder
return _charSet != 0;
}
}
public TypeLayout Layout
{
get
{
VerifySealed(expected: true);
Debug.Assert(HasStructLayoutAttribute);
return _layout;
}
}
public CharSet MarshallingCharSet
{
get
{
VerifySealed(expected: true);
Debug.Assert(HasStructLayoutAttribute);
return _charSet;
}
}
#endregion
#region SecurityCriticalAttribute and SecuritySafeCriticalAttribute
private bool _hasSecurityCriticalAttributes;
public bool HasSecurityCriticalAttributes
{
get
{
VerifySealed(expected: true);
return _hasSecurityCriticalAttributes;
}
set
{
VerifySealed(expected: false);
_hasSecurityCriticalAttributes = value;
SetDataStored();
}
}
#endregion
#region ExcludeFromCodeCoverageAttribute
private bool _hasExcludeFromCodeCoverageAttribute;
public bool HasExcludeFromCodeCoverageAttribute
{
get
{
VerifySealed(expected: true);
return _hasExcludeFromCodeCoverageAttribute;
}
set
{
VerifySealed(expected: false);
_hasExcludeFromCodeCoverageAttribute = value;
SetDataStored();
}
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/NotificationOption2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
#if CODE_STYLE
using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources;
#endif
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <summary>
/// Offers different notification styles for enforcing
/// a code style. Under the hood, it simply maps to <see cref="DiagnosticSeverity"/>
/// </summary>
/// <remarks>
/// This also supports various properties for databinding.
/// </remarks>
/// <completionlist cref="NotificationOption2"/>
internal sealed partial class NotificationOption2 : IEquatable<NotificationOption2?>
{
/// <summary>
/// Name for the notification option.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Diagnostic severity associated with notification option.
/// </summary>
public ReportDiagnostic Severity
{
get;
set;
}
/// <summary>
/// Notification option to disable or suppress an option with <see cref="ReportDiagnostic.Suppress"/>.
/// </summary>
public static readonly NotificationOption2 None = new(WorkspacesResources.None, ReportDiagnostic.Suppress);
/// <summary>
/// Notification option for a silent or hidden option with <see cref="ReportDiagnostic.Hidden"/>.
/// </summary>
public static readonly NotificationOption2 Silent = new(WorkspacesResources.Refactoring_Only, ReportDiagnostic.Hidden);
/// <summary>
/// Notification option for a suggestion or an info option with <see cref="ReportDiagnostic.Info"/>.
/// </summary>
public static readonly NotificationOption2 Suggestion = new(WorkspacesResources.Suggestion, ReportDiagnostic.Info);
/// <summary>
/// Notification option for a warning option with <see cref="ReportDiagnostic.Warn"/>.
/// </summary>
public static readonly NotificationOption2 Warning = new(WorkspacesResources.Warning, ReportDiagnostic.Warn);
/// <summary>
/// Notification option for an error option with <see cref="ReportDiagnostic.Error"/>.
/// </summary>
public static readonly NotificationOption2 Error = new(WorkspacesResources.Error, ReportDiagnostic.Error);
private NotificationOption2(string name, ReportDiagnostic severity)
{
Name = name;
Severity = severity;
}
public override string ToString() => Name;
public override bool Equals(object? obj)
=> ReferenceEquals(this, obj);
public bool Equals(NotificationOption2? notificationOption2)
=> ReferenceEquals(this, notificationOption2);
public override int GetHashCode()
{
var hash = this.Name.GetHashCode();
hash = unchecked((hash * (int)0xA5555529) + this.Severity.GetHashCode());
return hash;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
#if CODE_STYLE
using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources;
#endif
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <summary>
/// Offers different notification styles for enforcing
/// a code style. Under the hood, it simply maps to <see cref="DiagnosticSeverity"/>
/// </summary>
/// <remarks>
/// This also supports various properties for databinding.
/// </remarks>
/// <completionlist cref="NotificationOption2"/>
internal sealed partial class NotificationOption2 : IEquatable<NotificationOption2?>
{
/// <summary>
/// Name for the notification option.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Diagnostic severity associated with notification option.
/// </summary>
public ReportDiagnostic Severity
{
get;
set;
}
/// <summary>
/// Notification option to disable or suppress an option with <see cref="ReportDiagnostic.Suppress"/>.
/// </summary>
public static readonly NotificationOption2 None = new(WorkspacesResources.None, ReportDiagnostic.Suppress);
/// <summary>
/// Notification option for a silent or hidden option with <see cref="ReportDiagnostic.Hidden"/>.
/// </summary>
public static readonly NotificationOption2 Silent = new(WorkspacesResources.Refactoring_Only, ReportDiagnostic.Hidden);
/// <summary>
/// Notification option for a suggestion or an info option with <see cref="ReportDiagnostic.Info"/>.
/// </summary>
public static readonly NotificationOption2 Suggestion = new(WorkspacesResources.Suggestion, ReportDiagnostic.Info);
/// <summary>
/// Notification option for a warning option with <see cref="ReportDiagnostic.Warn"/>.
/// </summary>
public static readonly NotificationOption2 Warning = new(WorkspacesResources.Warning, ReportDiagnostic.Warn);
/// <summary>
/// Notification option for an error option with <see cref="ReportDiagnostic.Error"/>.
/// </summary>
public static readonly NotificationOption2 Error = new(WorkspacesResources.Error, ReportDiagnostic.Error);
private NotificationOption2(string name, ReportDiagnostic severity)
{
Name = name;
Severity = severity;
}
public override string ToString() => Name;
public override bool Equals(object? obj)
=> ReferenceEquals(this, obj);
public bool Equals(NotificationOption2? notificationOption2)
=> ReferenceEquals(this, notificationOption2);
public override int GetHashCode()
{
var hash = this.Name.GetHashCode();
hash = unchecked((hash * (int)0xA5555529) + this.Severity.GetHashCode());
return hash;
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/IndexedTypeParameterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IndexedTypeParameterTests
{
[Fact]
public void TestTake()
{
var zero = IndexedTypeParameterSymbol.TakeSymbols(0);
Assert.Equal(0, zero.Length);
var five = IndexedTypeParameterSymbol.TakeSymbols(5);
Assert.Equal(5, five.Length);
Assert.Equal(five[0], IndexedTypeParameterSymbol.GetTypeParameter(0));
Assert.Equal(five[1], IndexedTypeParameterSymbol.GetTypeParameter(1));
Assert.Equal(five[2], IndexedTypeParameterSymbol.GetTypeParameter(2));
Assert.Equal(five[3], IndexedTypeParameterSymbol.GetTypeParameter(3));
Assert.Equal(five[4], IndexedTypeParameterSymbol.GetTypeParameter(4));
var fifty = IndexedTypeParameterSymbol.TakeSymbols(50);
Assert.Equal(50, fifty.Length);
// prove they are all unique
var set = new HashSet<TypeParameterSymbol>(fifty);
Assert.Equal(50, set.Count);
var fiveHundred = IndexedTypeParameterSymbol.TakeSymbols(500);
Assert.Equal(500, fiveHundred.Length);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IndexedTypeParameterTests
{
[Fact]
public void TestTake()
{
var zero = IndexedTypeParameterSymbol.TakeSymbols(0);
Assert.Equal(0, zero.Length);
var five = IndexedTypeParameterSymbol.TakeSymbols(5);
Assert.Equal(5, five.Length);
Assert.Equal(five[0], IndexedTypeParameterSymbol.GetTypeParameter(0));
Assert.Equal(five[1], IndexedTypeParameterSymbol.GetTypeParameter(1));
Assert.Equal(five[2], IndexedTypeParameterSymbol.GetTypeParameter(2));
Assert.Equal(five[3], IndexedTypeParameterSymbol.GetTypeParameter(3));
Assert.Equal(five[4], IndexedTypeParameterSymbol.GetTypeParameter(4));
var fifty = IndexedTypeParameterSymbol.TakeSymbols(50);
Assert.Equal(50, fifty.Length);
// prove they are all unique
var set = new HashSet<TypeParameterSymbol>(fifty);
Assert.Equal(50, set.Count);
var fiveHundred = IndexedTypeParameterSymbol.TakeSymbols(500);
Assert.Equal(500, fiveHundred.Length);
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_StringIds.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Concurrent;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.SQLite.Interop;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
using Microsoft.CodeAnalysis.Storage;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal partial class SQLitePersistentStorage
{
private readonly ConcurrentDictionary<string, int> _stringToIdMap = new();
private int? TryGetStringId(SqlConnection connection, string? value, bool allowWrite)
{
// Null strings are not supported at all. Just ignore these. Any read/writes
// to null values will fail and will return 'false/null' to indicate failure
// (which is part of the documented contract of the persistence layer API).
if (value == null)
{
return null;
}
// First see if we've cached the ID for this value locally. If so, just return
// what we already have.
if (_stringToIdMap.TryGetValue(value, out var existingId))
{
return existingId;
}
// Otherwise, try to get or add the string to the string table in the database.
var id = TryGetStringIdFromDatabase(connection, value, allowWrite);
if (id != null)
{
_stringToIdMap[value] = id.Value;
}
return id;
}
private int? TryGetStringIdFromDatabase(SqlConnection connection, string value, bool allowWrite)
{
// We're reading or writing. This can be under either of our schedulers.
Contract.ThrowIfFalse(
TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler ||
TaskScheduler.Current == _connectionPoolService.Scheduler.ConcurrentScheduler);
// First, check if we can find that string in the string table.
var stringId = TryGetStringIdFromDatabaseWorker(connection, value, canReturnNull: true);
if (stringId != null)
{
// Found the value already in the db. Another process (or thread) might have added it.
// We're done at this point.
return stringId;
}
// If we're in a context where our caller doesn't have the write lock, give up now. They will
// call back in with the write lock to allow safe adding of this db ID after this.
if (!allowWrite)
return null;
// We're writing. This better always be under the exclusive scheduler.
Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler);
// The string wasn't in the db string table. Add it. Note: this may fail if some
// other thread/process beats us there as this table has a 'unique' constraint on the
// values.
try
{
stringId = connection.RunInTransaction(
static t => t.self.InsertStringIntoDatabase_MustRunInTransaction(t.connection, t.value),
(self: this, connection, value));
Contract.ThrowIfTrue(stringId == null);
return stringId;
}
catch (SqlException ex) when (ex.Result == Result.CONSTRAINT)
{
// We got a constraint violation. This means someone else beat us to adding this
// string to the string-table. We should always be able to find the string now.
stringId = TryGetStringIdFromDatabaseWorker(connection, value, canReturnNull: false);
return stringId;
}
catch (Exception ex)
{
// Some other error occurred. Log it and return nothing.
StorageDatabaseLogger.LogException(ex);
}
return null;
}
private int InsertStringIntoDatabase_MustRunInTransaction(SqlConnection connection, string value)
{
if (!connection.IsInTransaction)
{
throw new InvalidOperationException("Must call this while connection has transaction open");
}
var id = -1;
using (var resettableStatement = connection.GetResettableStatement(_insert_into_string_table_values_0))
{
var statement = resettableStatement.Statement;
// SQLite bindings are 1-based.
statement.BindStringParameter(parameterIndex: 1, value: value);
// Try to insert the value. This may throw a constraint exception if some
// other process beat us to this string.
statement.Step();
// Successfully added the string. The ID for it can be retrieved as the LastInsertRowId
// for the db. This is also safe to call because we must be in a transaction when this
// is invoked.
id = connection.LastInsertRowId();
}
Contract.ThrowIfTrue(id == -1);
return id;
}
private int? TryGetStringIdFromDatabaseWorker(
SqlConnection connection, string value, bool canReturnNull)
{
try
{
using var resettableStatement = connection.GetResettableStatement(_select_star_from_string_table_where_0_limit_one);
var statement = resettableStatement.Statement;
// SQLite's binding indices are 1-based.
statement.BindStringParameter(parameterIndex: 1, value: value);
var stepResult = statement.Step();
if (stepResult == Result.ROW)
{
return statement.GetInt32At(columnIndex: 0);
}
}
catch (Exception ex)
{
// If we simply failed to even talk to the DB then we have to bail out. There's
// nothing we can accomplish at this point.
StorageDatabaseLogger.LogException(ex);
return null;
}
// No item with this value in the table.
if (canReturnNull)
{
return null;
}
// This should not be possible. We only called here if we got a constraint violation.
// So how could we then not find the string in the table?
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.Concurrent;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.SQLite.Interop;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
using Microsoft.CodeAnalysis.Storage;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal partial class SQLitePersistentStorage
{
private readonly ConcurrentDictionary<string, int> _stringToIdMap = new();
private int? TryGetStringId(SqlConnection connection, string? value, bool allowWrite)
{
// Null strings are not supported at all. Just ignore these. Any read/writes
// to null values will fail and will return 'false/null' to indicate failure
// (which is part of the documented contract of the persistence layer API).
if (value == null)
{
return null;
}
// First see if we've cached the ID for this value locally. If so, just return
// what we already have.
if (_stringToIdMap.TryGetValue(value, out var existingId))
{
return existingId;
}
// Otherwise, try to get or add the string to the string table in the database.
var id = TryGetStringIdFromDatabase(connection, value, allowWrite);
if (id != null)
{
_stringToIdMap[value] = id.Value;
}
return id;
}
private int? TryGetStringIdFromDatabase(SqlConnection connection, string value, bool allowWrite)
{
// We're reading or writing. This can be under either of our schedulers.
Contract.ThrowIfFalse(
TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler ||
TaskScheduler.Current == _connectionPoolService.Scheduler.ConcurrentScheduler);
// First, check if we can find that string in the string table.
var stringId = TryGetStringIdFromDatabaseWorker(connection, value, canReturnNull: true);
if (stringId != null)
{
// Found the value already in the db. Another process (or thread) might have added it.
// We're done at this point.
return stringId;
}
// If we're in a context where our caller doesn't have the write lock, give up now. They will
// call back in with the write lock to allow safe adding of this db ID after this.
if (!allowWrite)
return null;
// We're writing. This better always be under the exclusive scheduler.
Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler);
// The string wasn't in the db string table. Add it. Note: this may fail if some
// other thread/process beats us there as this table has a 'unique' constraint on the
// values.
try
{
stringId = connection.RunInTransaction(
static t => t.self.InsertStringIntoDatabase_MustRunInTransaction(t.connection, t.value),
(self: this, connection, value));
Contract.ThrowIfTrue(stringId == null);
return stringId;
}
catch (SqlException ex) when (ex.Result == Result.CONSTRAINT)
{
// We got a constraint violation. This means someone else beat us to adding this
// string to the string-table. We should always be able to find the string now.
stringId = TryGetStringIdFromDatabaseWorker(connection, value, canReturnNull: false);
return stringId;
}
catch (Exception ex)
{
// Some other error occurred. Log it and return nothing.
StorageDatabaseLogger.LogException(ex);
}
return null;
}
private int InsertStringIntoDatabase_MustRunInTransaction(SqlConnection connection, string value)
{
if (!connection.IsInTransaction)
{
throw new InvalidOperationException("Must call this while connection has transaction open");
}
var id = -1;
using (var resettableStatement = connection.GetResettableStatement(_insert_into_string_table_values_0))
{
var statement = resettableStatement.Statement;
// SQLite bindings are 1-based.
statement.BindStringParameter(parameterIndex: 1, value: value);
// Try to insert the value. This may throw a constraint exception if some
// other process beat us to this string.
statement.Step();
// Successfully added the string. The ID for it can be retrieved as the LastInsertRowId
// for the db. This is also safe to call because we must be in a transaction when this
// is invoked.
id = connection.LastInsertRowId();
}
Contract.ThrowIfTrue(id == -1);
return id;
}
private int? TryGetStringIdFromDatabaseWorker(
SqlConnection connection, string value, bool canReturnNull)
{
try
{
using var resettableStatement = connection.GetResettableStatement(_select_star_from_string_table_where_0_limit_one);
var statement = resettableStatement.Statement;
// SQLite's binding indices are 1-based.
statement.BindStringParameter(parameterIndex: 1, value: value);
var stepResult = statement.Step();
if (stepResult == Result.ROW)
{
return statement.GetInt32At(columnIndex: 0);
}
}
catch (Exception ex)
{
// If we simply failed to even talk to the DB then we have to bail out. There's
// nothing we can accomplish at this point.
StorageDatabaseLogger.LogException(ex);
return null;
}
// No item with this value in the table.
if (canReturnNull)
{
return null;
}
// This should not be possible. We only called here if we got a constraint violation.
// So how could we then not find the string in the table?
throw new InvalidOperationException();
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SyntaxListExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SyntaxListExtensions
<Extension()>
Public Function RemoveRange(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, count As Integer) As SyntaxList(Of T)
Dim result = New List(Of T)(syntaxList)
result.RemoveRange(index, count)
Return SyntaxFactory.List(result)
End Function
<Extension()>
Public Function ToSyntaxList(Of T As SyntaxNode)(sequence As IEnumerable(Of T)) As SyntaxList(Of T)
Return SyntaxFactory.List(sequence)
End Function
<Extension()>
Public Function Insert(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, item As T) As SyntaxList(Of T)
Return syntaxList.Take(index).Concat(item).Concat(syntaxList.Skip(index)).ToSyntaxList
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SyntaxListExtensions
<Extension()>
Public Function RemoveRange(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, count As Integer) As SyntaxList(Of T)
Dim result = New List(Of T)(syntaxList)
result.RemoveRange(index, count)
Return SyntaxFactory.List(result)
End Function
<Extension()>
Public Function ToSyntaxList(Of T As SyntaxNode)(sequence As IEnumerable(Of T)) As SyntaxList(Of T)
Return SyntaxFactory.List(sequence)
End Function
<Extension()>
Public Function Insert(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, item As T) As SyntaxList(Of T)
Return syntaxList.Take(index).Concat(item).Concat(syntaxList.Skip(index)).ToSyntaxList
End Function
End Module
End Namespace
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hans.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hans" original="../Resources.resx">
<body>
<trans-unit id="RemoveAndSortNamespacesWithAccelerator">
<source>Remove &and Sort Namespaces</source>
<target state="translated">删除命名空间并排序(&A)</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnnecessaryNamespaces">
<source>Remove Unnecessary Namespaces</source>
<target state="translated">删除不必要的命名空间</target>
<note />
</trans-unit>
<trans-unit id="Sort_Namespaces">
<source>&Sort Namespaces</source>
<target state="translated">对命名空间排序(&S)</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hans" original="../Resources.resx">
<body>
<trans-unit id="RemoveAndSortNamespacesWithAccelerator">
<source>Remove &and Sort Namespaces</source>
<target state="translated">删除命名空间并排序(&A)</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnnecessaryNamespaces">
<source>Remove Unnecessary Namespaces</source>
<target state="translated">删除不必要的命名空间</target>
<note />
</trans-unit>
<trans-unit id="Sort_Namespaces">
<source>&Sort Namespaces</source>
<target state="translated">对命名空间排序(&S)</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Core/Portable/Syntax/SyntaxTree.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The parsed representation of a source document.
/// </summary>
public abstract class SyntaxTree
{
/// <summary>
/// Cached value for empty <see cref="DiagnosticOptions"/>.
/// </summary>
protected internal static readonly ImmutableDictionary<string, ReportDiagnostic> EmptyDiagnosticOptions =
ImmutableDictionary.Create<string, ReportDiagnostic>(CaseInsensitiveComparison.Comparer);
private ImmutableArray<byte> _lazyChecksum;
private SourceHashAlgorithm _lazyHashAlgorithm;
/// <summary>
/// The path of the source document file.
/// </summary>
/// <remarks>
/// If this syntax tree is not associated with a file, this value can be empty.
/// The path shall not be null.
///
/// The file doesn't need to exist on disk. The path is opaque to the compiler.
/// The only requirement on the path format is that the implementations of
/// <see cref="SourceReferenceResolver"/>, <see cref="XmlReferenceResolver"/> and <see cref="MetadataReferenceResolver"/>
/// passed to the compilation that contains the tree understand it.
///
/// Clients must also not assume that the values of this property are unique
/// within a Compilation.
///
/// The path is used as follows:
/// - When debug information is emitted, this path is embedded in the debug information.
/// - When resolving and normalizing relative paths in #r, #load, #line/#ExternalSource,
/// #pragma checksum, #ExternalChecksum directives, XML doc comment include elements, etc.
/// </remarks>
public abstract string FilePath { get; }
/// <summary>
/// Returns true if this syntax tree has a root with SyntaxKind "CompilationUnit".
/// </summary>
public abstract bool HasCompilationUnitRoot { get; }
/// <summary>
/// The options used by the parser to produce the syntax tree.
/// </summary>
public ParseOptions Options
{
get
{
return this.OptionsCore;
}
}
/// <summary>
/// The options used by the parser to produce the syntax tree.
/// </summary>
protected abstract ParseOptions OptionsCore { get; }
/// <summary>
/// Option to specify custom behavior for each warning in this tree.
/// </summary>
/// <returns>
/// A map from diagnostic ID to diagnostic reporting level. The diagnostic
/// ID string may be case insensitive depending on the language.
/// </returns>
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public virtual ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => EmptyDiagnosticOptions;
/// <summary>
/// The length of the text of the syntax tree.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// Gets the syntax tree's text if it is available.
/// </summary>
public abstract bool TryGetText([NotNullWhen(true)] out SourceText? text);
/// <summary>
/// Gets the text of the source document.
/// </summary>
public abstract SourceText GetText(CancellationToken cancellationToken = default);
/// <summary>
/// The text encoding of the source document.
/// </summary>
public abstract Encoding? Encoding { get; }
/// <summary>
/// Gets the text of the source document asynchronously.
/// </summary>
/// <remarks>
/// By default, the work associated with this method will be executed immediately on the current thread.
/// Implementations that wish to schedule this work differently should override <see cref="GetTextAsync(CancellationToken)"/>.
/// </remarks>
public virtual Task<SourceText> GetTextAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(this.TryGetText(out SourceText? text) ? text : this.GetText(cancellationToken));
}
/// <summary>
/// Gets the root of the syntax tree if it is available.
/// </summary>
public bool TryGetRoot([NotNullWhen(true)] out SyntaxNode? root)
{
return TryGetRootCore(out root);
}
/// <summary>
/// Gets the root of the syntax tree if it is available.
/// </summary>
protected abstract bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root);
/// <summary>
/// Gets the root node of the syntax tree, causing computation if necessary.
/// </summary>
public SyntaxNode GetRoot(CancellationToken cancellationToken = default)
{
return GetRootCore(cancellationToken);
}
/// <summary>
/// Gets the root node of the syntax tree, causing computation if necessary.
/// </summary>
protected abstract SyntaxNode GetRootCore(CancellationToken cancellationToken);
/// <summary>
/// Gets the root node of the syntax tree asynchronously.
/// </summary>
public Task<SyntaxNode> GetRootAsync(CancellationToken cancellationToken = default)
{
return GetRootAsyncCore(cancellationToken);
}
/// <summary>
/// Gets the root node of the syntax tree asynchronously.
/// </summary>
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Public API.")]
protected abstract Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken);
/// <summary>
/// Create a new syntax tree based off this tree using a new source text.
///
/// If the new source text is a minor change from the current source text an incremental
/// parse will occur reusing most of the current syntax tree internal data. Otherwise, a
/// full parse will occur using the new source text.
/// </summary>
public abstract SyntaxTree WithChangedText(SourceText newText);
/// <summary>
/// Gets a list of all the diagnostics in the syntax tree.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default);
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has the specified node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node);
/// <summary>
/// Gets a list of all the diagnostics associated with the token and any related trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token);
/// <summary>
/// Gets a list of all the diagnostics associated with the trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia);
/// <summary>
/// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or
/// associated with the token and its related trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken);
/// <summary>
/// Gets the location in terms of path, line and column for a given span.
/// </summary>
/// <param name="span">Span within the tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.
/// The values are not affected by line mapping directives (<c>#line</c>).
/// </returns>
public abstract FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the location in terms of path, line and column after applying source line mapping directives
/// (<c>#line</c> in C# or <c>#ExternalSource</c> in VB).
/// </summary>
/// <param name="span">Span within the tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.
///
/// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>,
/// otherwise it's <see cref="FilePath"/>.
///
/// A location path is considered mapped if it is preceded by a line mapping directive that
/// either specifies an explicit file path or is <c>#line default</c>.
/// </returns>
public abstract FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default);
/// <summary>
/// Returns empty sequence if there are no line mapping directives in the tree.
/// Otherwise, returns a sequence of pairs of spans: each describing a mapping of a span of the tree between two consecutive #line directives.
/// If the first directive is not on the first line the first pair describes mapping of the span preceding the first directive.
/// The last pair of the sequence describes mapping of the span following the last #line directive.
/// </summary>
/// <returns>
/// Empty sequence if the tree does not contain a line mapping directive.
/// Otherwise a non-empty sequence of <see cref="LineMapping"/>.
/// </returns>
public abstract IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default);
/// <summary>
/// Returns the visibility for the line at the given position.
/// </summary>
/// <param name="position">The position to check.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public virtual LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default)
{
return LineVisibility.Visible;
}
/// <summary>
/// Gets a FileLinePositionSpan for a TextSpan and the information whether this span is considered to be hidden or not.
/// FileLinePositionSpans are used primarily for diagnostics and source locations.
/// This method combines a call to GetLineSpan and IsHiddenPosition.
/// </summary>
/// <param name="span"></param>
/// <param name="isHiddenPosition">Returns a boolean indicating whether this span is considered hidden or not.</param>
/// <remarks>This function is being called only in the context of sequence point creation and therefore interprets the
/// LineVisibility accordingly (BeforeFirstRemappingDirective -> Visible).</remarks>
internal virtual FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition)
{
isHiddenPosition = GetLineVisibility(span.Start) == LineVisibility.Hidden;
return GetMappedLineSpan(span);
}
/// <summary>
/// Returns a path for particular location in source that is presented to the user.
/// </summary>
/// <remarks>
/// Used for implementation of <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>
/// or for embedding source paths in error messages.
///
/// Unlike Dev12 we do account for #line and #ExternalSource directives when determining value for
/// <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>.
/// </remarks>
internal string GetDisplayPath(TextSpan span, SourceReferenceResolver? resolver)
{
var mappedSpan = GetMappedLineSpan(span);
if (resolver == null || mappedSpan.Path.IsEmpty())
{
return mappedSpan.Path;
}
return resolver.NormalizePath(mappedSpan.Path, baseFilePath: mappedSpan.HasMappedPath ? FilePath : null) ?? mappedSpan.Path;
}
/// <summary>
/// Returns a line number for particular location in source that is presented to the user.
/// </summary>
/// <remarks>
/// Used for implementation of <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>
/// or for embedding source line numbers in error messages.
///
/// Unlike Dev12 we do account for #line and #ExternalSource directives when determining value for
/// <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>.
/// </remarks>
internal int GetDisplayLineNumber(TextSpan span)
{
// display line numbers are 1-based
return GetMappedLineSpan(span).StartLinePosition.Line + 1;
}
/// <summary>
/// Are there any hidden regions in the tree?
/// </summary>
/// <returns>True if there is at least one hidden region.</returns>
public abstract bool HasHiddenRegions();
/// <summary>
/// Returns a list of the changed regions between this tree and the specified tree. The list is conservative for
/// performance reasons. It may return larger regions than what has actually changed.
/// </summary>
public abstract IList<TextSpan> GetChangedSpans(SyntaxTree syntaxTree);
/// <summary>
/// Gets a location for the specified text span.
/// </summary>
public abstract Location GetLocation(TextSpan span);
/// <summary>
/// Determines if two trees are the same, disregarding trivia differences.
/// </summary>
/// <param name="tree">The tree to compare against.</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 abstract bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false);
/// <summary>
/// Gets a SyntaxReference for a specified syntax node. SyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
public abstract SyntaxReference GetReference(SyntaxNode node);
/// <summary>
/// Gets a list of text changes that when applied to the old tree produce this tree.
/// </summary>
/// <param name="oldTree">The old tree.</param>
/// <remarks>The list of changes may be different than the original changes that produced
/// this tree.</remarks>
public abstract IList<TextChange> GetChanges(SyntaxTree oldTree);
/// <summary>
/// Gets the checksum + algorithm id to use in the PDB.
/// </summary>
internal Cci.DebugSourceInfo GetDebugSourceInfo()
{
if (_lazyChecksum.IsDefault)
{
var text = this.GetText();
_lazyChecksum = text.GetChecksum();
_lazyHashAlgorithm = text.ChecksumAlgorithm;
}
Debug.Assert(!_lazyChecksum.IsDefault);
Debug.Assert(_lazyHashAlgorithm != default(SourceHashAlgorithm));
// NOTE: If this tree is to be embedded, it's debug source info should have
// been obtained via EmbeddedText.GetDebugSourceInfo() and not here.
return new Cci.DebugSourceInfo(_lazyChecksum, _lazyHashAlgorithm);
}
/// <summary>
/// Returns a new tree whose root and options are as specified and other properties are copied from the current tree.
/// </summary>
public abstract SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options);
/// <summary>
/// Returns a new tree whose <see cref="FilePath"/> is the specified node and other properties are copied from the current tree.
/// </summary>
public abstract SyntaxTree WithFilePath(string path);
/// <summary>
/// Returns a new tree whose <see cref="DiagnosticOptions" /> are the specified value and other properties are copied
/// from the current tree.
/// </summary>
/// <param name="options">
/// A mapping from diagnostic id to diagnostic reporting level. The diagnostic ID may be case-sensitive depending
/// on the language.
/// </param>
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public virtual SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a <see cref="String" /> that represents the entire source text of this <see cref="SyntaxTree"/>.
/// </summary>
public override string ToString()
{
return this.GetText(CancellationToken.None).ToString();
}
internal virtual bool SupportsLocations
{
get { return this.HasCompilationUnitRoot; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The parsed representation of a source document.
/// </summary>
public abstract class SyntaxTree
{
/// <summary>
/// Cached value for empty <see cref="DiagnosticOptions"/>.
/// </summary>
protected internal static readonly ImmutableDictionary<string, ReportDiagnostic> EmptyDiagnosticOptions =
ImmutableDictionary.Create<string, ReportDiagnostic>(CaseInsensitiveComparison.Comparer);
private ImmutableArray<byte> _lazyChecksum;
private SourceHashAlgorithm _lazyHashAlgorithm;
/// <summary>
/// The path of the source document file.
/// </summary>
/// <remarks>
/// If this syntax tree is not associated with a file, this value can be empty.
/// The path shall not be null.
///
/// The file doesn't need to exist on disk. The path is opaque to the compiler.
/// The only requirement on the path format is that the implementations of
/// <see cref="SourceReferenceResolver"/>, <see cref="XmlReferenceResolver"/> and <see cref="MetadataReferenceResolver"/>
/// passed to the compilation that contains the tree understand it.
///
/// Clients must also not assume that the values of this property are unique
/// within a Compilation.
///
/// The path is used as follows:
/// - When debug information is emitted, this path is embedded in the debug information.
/// - When resolving and normalizing relative paths in #r, #load, #line/#ExternalSource,
/// #pragma checksum, #ExternalChecksum directives, XML doc comment include elements, etc.
/// </remarks>
public abstract string FilePath { get; }
/// <summary>
/// Returns true if this syntax tree has a root with SyntaxKind "CompilationUnit".
/// </summary>
public abstract bool HasCompilationUnitRoot { get; }
/// <summary>
/// The options used by the parser to produce the syntax tree.
/// </summary>
public ParseOptions Options
{
get
{
return this.OptionsCore;
}
}
/// <summary>
/// The options used by the parser to produce the syntax tree.
/// </summary>
protected abstract ParseOptions OptionsCore { get; }
/// <summary>
/// Option to specify custom behavior for each warning in this tree.
/// </summary>
/// <returns>
/// A map from diagnostic ID to diagnostic reporting level. The diagnostic
/// ID string may be case insensitive depending on the language.
/// </returns>
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public virtual ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => EmptyDiagnosticOptions;
/// <summary>
/// The length of the text of the syntax tree.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// Gets the syntax tree's text if it is available.
/// </summary>
public abstract bool TryGetText([NotNullWhen(true)] out SourceText? text);
/// <summary>
/// Gets the text of the source document.
/// </summary>
public abstract SourceText GetText(CancellationToken cancellationToken = default);
/// <summary>
/// The text encoding of the source document.
/// </summary>
public abstract Encoding? Encoding { get; }
/// <summary>
/// Gets the text of the source document asynchronously.
/// </summary>
/// <remarks>
/// By default, the work associated with this method will be executed immediately on the current thread.
/// Implementations that wish to schedule this work differently should override <see cref="GetTextAsync(CancellationToken)"/>.
/// </remarks>
public virtual Task<SourceText> GetTextAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(this.TryGetText(out SourceText? text) ? text : this.GetText(cancellationToken));
}
/// <summary>
/// Gets the root of the syntax tree if it is available.
/// </summary>
public bool TryGetRoot([NotNullWhen(true)] out SyntaxNode? root)
{
return TryGetRootCore(out root);
}
/// <summary>
/// Gets the root of the syntax tree if it is available.
/// </summary>
protected abstract bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root);
/// <summary>
/// Gets the root node of the syntax tree, causing computation if necessary.
/// </summary>
public SyntaxNode GetRoot(CancellationToken cancellationToken = default)
{
return GetRootCore(cancellationToken);
}
/// <summary>
/// Gets the root node of the syntax tree, causing computation if necessary.
/// </summary>
protected abstract SyntaxNode GetRootCore(CancellationToken cancellationToken);
/// <summary>
/// Gets the root node of the syntax tree asynchronously.
/// </summary>
public Task<SyntaxNode> GetRootAsync(CancellationToken cancellationToken = default)
{
return GetRootAsyncCore(cancellationToken);
}
/// <summary>
/// Gets the root node of the syntax tree asynchronously.
/// </summary>
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Public API.")]
protected abstract Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken);
/// <summary>
/// Create a new syntax tree based off this tree using a new source text.
///
/// If the new source text is a minor change from the current source text an incremental
/// parse will occur reusing most of the current syntax tree internal data. Otherwise, a
/// full parse will occur using the new source text.
/// </summary>
public abstract SyntaxTree WithChangedText(SourceText newText);
/// <summary>
/// Gets a list of all the diagnostics in the syntax tree.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default);
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has the specified node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node);
/// <summary>
/// Gets a list of all the diagnostics associated with the token and any related trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token);
/// <summary>
/// Gets a list of all the diagnostics associated with the trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia);
/// <summary>
/// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or
/// associated with the token and its related trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public abstract IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken);
/// <summary>
/// Gets the location in terms of path, line and column for a given span.
/// </summary>
/// <param name="span">Span within the tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.
/// The values are not affected by line mapping directives (<c>#line</c>).
/// </returns>
public abstract FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the location in terms of path, line and column after applying source line mapping directives
/// (<c>#line</c> in C# or <c>#ExternalSource</c> in VB).
/// </summary>
/// <param name="span">Span within the tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.
///
/// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>,
/// otherwise it's <see cref="FilePath"/>.
///
/// A location path is considered mapped if it is preceded by a line mapping directive that
/// either specifies an explicit file path or is <c>#line default</c>.
/// </returns>
public abstract FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default);
/// <summary>
/// Returns empty sequence if there are no line mapping directives in the tree.
/// Otherwise, returns a sequence of pairs of spans: each describing a mapping of a span of the tree between two consecutive #line directives.
/// If the first directive is not on the first line the first pair describes mapping of the span preceding the first directive.
/// The last pair of the sequence describes mapping of the span following the last #line directive.
/// </summary>
/// <returns>
/// Empty sequence if the tree does not contain a line mapping directive.
/// Otherwise a non-empty sequence of <see cref="LineMapping"/>.
/// </returns>
public abstract IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default);
/// <summary>
/// Returns the visibility for the line at the given position.
/// </summary>
/// <param name="position">The position to check.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public virtual LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default)
{
return LineVisibility.Visible;
}
/// <summary>
/// Gets a FileLinePositionSpan for a TextSpan and the information whether this span is considered to be hidden or not.
/// FileLinePositionSpans are used primarily for diagnostics and source locations.
/// This method combines a call to GetLineSpan and IsHiddenPosition.
/// </summary>
/// <param name="span"></param>
/// <param name="isHiddenPosition">Returns a boolean indicating whether this span is considered hidden or not.</param>
/// <remarks>This function is being called only in the context of sequence point creation and therefore interprets the
/// LineVisibility accordingly (BeforeFirstRemappingDirective -> Visible).</remarks>
internal virtual FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition)
{
isHiddenPosition = GetLineVisibility(span.Start) == LineVisibility.Hidden;
return GetMappedLineSpan(span);
}
/// <summary>
/// Returns a path for particular location in source that is presented to the user.
/// </summary>
/// <remarks>
/// Used for implementation of <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>
/// or for embedding source paths in error messages.
///
/// Unlike Dev12 we do account for #line and #ExternalSource directives when determining value for
/// <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>.
/// </remarks>
internal string GetDisplayPath(TextSpan span, SourceReferenceResolver? resolver)
{
var mappedSpan = GetMappedLineSpan(span);
if (resolver == null || mappedSpan.Path.IsEmpty())
{
return mappedSpan.Path;
}
return resolver.NormalizePath(mappedSpan.Path, baseFilePath: mappedSpan.HasMappedPath ? FilePath : null) ?? mappedSpan.Path;
}
/// <summary>
/// Returns a line number for particular location in source that is presented to the user.
/// </summary>
/// <remarks>
/// Used for implementation of <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>
/// or for embedding source line numbers in error messages.
///
/// Unlike Dev12 we do account for #line and #ExternalSource directives when determining value for
/// <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>.
/// </remarks>
internal int GetDisplayLineNumber(TextSpan span)
{
// display line numbers are 1-based
return GetMappedLineSpan(span).StartLinePosition.Line + 1;
}
/// <summary>
/// Are there any hidden regions in the tree?
/// </summary>
/// <returns>True if there is at least one hidden region.</returns>
public abstract bool HasHiddenRegions();
/// <summary>
/// Returns a list of the changed regions between this tree and the specified tree. The list is conservative for
/// performance reasons. It may return larger regions than what has actually changed.
/// </summary>
public abstract IList<TextSpan> GetChangedSpans(SyntaxTree syntaxTree);
/// <summary>
/// Gets a location for the specified text span.
/// </summary>
public abstract Location GetLocation(TextSpan span);
/// <summary>
/// Determines if two trees are the same, disregarding trivia differences.
/// </summary>
/// <param name="tree">The tree to compare against.</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 abstract bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false);
/// <summary>
/// Gets a SyntaxReference for a specified syntax node. SyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
public abstract SyntaxReference GetReference(SyntaxNode node);
/// <summary>
/// Gets a list of text changes that when applied to the old tree produce this tree.
/// </summary>
/// <param name="oldTree">The old tree.</param>
/// <remarks>The list of changes may be different than the original changes that produced
/// this tree.</remarks>
public abstract IList<TextChange> GetChanges(SyntaxTree oldTree);
/// <summary>
/// Gets the checksum + algorithm id to use in the PDB.
/// </summary>
internal Cci.DebugSourceInfo GetDebugSourceInfo()
{
if (_lazyChecksum.IsDefault)
{
var text = this.GetText();
_lazyChecksum = text.GetChecksum();
_lazyHashAlgorithm = text.ChecksumAlgorithm;
}
Debug.Assert(!_lazyChecksum.IsDefault);
Debug.Assert(_lazyHashAlgorithm != default(SourceHashAlgorithm));
// NOTE: If this tree is to be embedded, it's debug source info should have
// been obtained via EmbeddedText.GetDebugSourceInfo() and not here.
return new Cci.DebugSourceInfo(_lazyChecksum, _lazyHashAlgorithm);
}
/// <summary>
/// Returns a new tree whose root and options are as specified and other properties are copied from the current tree.
/// </summary>
public abstract SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options);
/// <summary>
/// Returns a new tree whose <see cref="FilePath"/> is the specified node and other properties are copied from the current tree.
/// </summary>
public abstract SyntaxTree WithFilePath(string path);
/// <summary>
/// Returns a new tree whose <see cref="DiagnosticOptions" /> are the specified value and other properties are copied
/// from the current tree.
/// </summary>
/// <param name="options">
/// A mapping from diagnostic id to diagnostic reporting level. The diagnostic ID may be case-sensitive depending
/// on the language.
/// </param>
[Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public virtual SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a <see cref="String" /> that represents the entire source text of this <see cref="SyntaxTree"/>.
/// </summary>
public override string ToString()
{
return this.GetText(CancellationToken.None).ToString();
}
internal virtual bool SupportsLocations
{
get { return this.HasCompilationUnitRoot; }
}
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Compilers/Test/Resources/Core/WinRt/WinMDPrefixing.cs | // This is the source for WinMDPrefixing.winmd. To generate a copy of
// WinMDPrefixing.winmd executive the following commands:
// csc.exe /t:winmdobj WinMDPrefixing.cs
// winmdexp [/r: references to mscorlib, System.Runtime.dll, and windows.winmd] WinMDPrefixing.winmdobj
namespace WinMDPrefixing
{
public sealed class TestClass
: TestInterface
{
}
public interface TestInterface
{
}
public delegate void TestDelegate();
public struct TestStruct
{
public int TestField;
}
}
| // This is the source for WinMDPrefixing.winmd. To generate a copy of
// WinMDPrefixing.winmd executive the following commands:
// csc.exe /t:winmdobj WinMDPrefixing.cs
// winmdexp [/r: references to mscorlib, System.Runtime.dll, and windows.winmd] WinMDPrefixing.winmdobj
namespace WinMDPrefixing
{
public sealed class TestClass
: TestInterface
{
}
public interface TestInterface
{
}
public delegate void TestDelegate();
public struct TestStruct
{
public int TestField;
}
}
| -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Tools/ExternalAccess/Razor/PublicAPI.Unshipped.txt | -1 |
|||
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../VSPackage.resx">
<body>
<trans-unit id="101">
<source>Visual Basic</source>
<target state="translated">Visual Basic</target>
<note>Used anywhere the string is needed (that is, everywhere.)</note>
</trans-unit>
<trans-unit id="1012">
<source>Visual Basic Editor with Encoding</source>
<target state="translated">Visual Basic Editor con codifica</target>
<note />
</trans-unit>
<trans-unit id="1013">
<source>Visual Basic Editor</source>
<target state="translated">Visual Basic Editor</target>
<note />
</trans-unit>
<trans-unit id="10160">
<source>Underline reassigned variables;Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme;Inheritance Margin;Import Directives;</source>
<target state="needs-review-translation">Visualizza suggerimenti inline;Inserimento automatico di costrutti End;Modifica impostazioni di riformattazione;Modifica modalità struttura;Inserimento automatico di membri Interface e MustOverride;Mostra o nascondi separatori di riga routine;Attiva o disattiva i suggerimenti per la correzione degli errori;Attiva o disattiva l'evidenziazione di riferimenti e parole chiave;Regex;Colora espressioni regolari;Evidenzia i componenti correlati sotto il cursore;Segnala espressioni regolari non valide;regex;espressione regolare;Usa colori migliorati;Combinazione colori editor;</target>
<note>Advanced options page keywords</note>
</trans-unit>
<trans-unit id="102">
<source>Advanced</source>
<target state="translated">Avanzate</target>
<note>"Advanced" node under Tools >Options, Basic editor.</note>
</trans-unit>
<trans-unit id="103">
<source>Basic</source>
<target state="translated">Di base</target>
<note>"Basic" node in profile Import/Export.</note>
</trans-unit>
<trans-unit id="104">
<source>Basic Editor</source>
<target state="translated">Basic Editor</target>
<note>"Basic Editor" node in profile Import/Export.</note>
</trans-unit>
<trans-unit id="105">
<source>Options that control general editor features including Intellisense statement completion, line number display, and single-click URL navigation.</source>
<target state="translated">Opzioni che controllano le funzionalità generiche dell'editor, tra cui il completamento Intellisense delle istruzioni, la visualizzazione del numero di riga e l'apertura di URL con clic singolo.</target>
<note>"Basic" node help text in profile Import/Export.</note>
</trans-unit>
<trans-unit id="106">
<source>Options that control Visual Basic editor features including automatic insertion of end constructs, procedure line separators, and automatic code formatting.</source>
<target state="translated">Opzioni che controllano le funzionalità di Visual Basic Editor, tra cui l'inserimento automatico di costrutti End, i separatori di riga routine e la formattazione automatica del codice.</target>
<note>"Basic Editor" node help text in profile Import/Export.</note>
</trans-unit>
<trans-unit id="107">
<source>Optimizes the environment so you can focus on building world-class applications. This collection of settings contains customizations to the window layout, command menus and keyboard shortcuts to make common Visual Basic commands more accessible.</source>
<target state="translated">Ottimizza l'ambiente in modo da favorire la compilazione di applicazioni di qualità elevata. Questa raccolta di impostazioni contiene personalizzazioni relative a layout della finestra, menu dei comandi e tasti di scelta rapida per rendere più accessibili i comandi più usati di Visual Basic.</target>
<note>Profile description in profile Reset All Settings.</note>
</trans-unit>
<trans-unit id="108">
<source>Microsoft Visual Basic</source>
<target state="translated">Microsoft Visual Basic</target>
<note>Used for String in Tools > Options, Text Editor, File Extensions</note>
</trans-unit>
<trans-unit id="109">
<source>Code Style</source>
<target state="translated">Stile codice</target>
<note>"Code Style" category node under Tools >Options, Basic editor.</note>
</trans-unit>
<trans-unit id="10161">
<source>Qualify with Me;Prefer intrinsic types;Style;Code Style</source>
<target state="translated">Qualifica con utente;Preferisci tipi intrinseci;Stile;Stile codice</target>
<note>Code Style options page keywords</note>
</trans-unit>
<trans-unit id="110">
<source>Naming</source>
<target state="translated">Denominazione</target>
<note>"Naming Style" node under Tools >Options > Basic editor >Code Style.</note>
</trans-unit>
<trans-unit id="10162">
<source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source>
<target state="translated">Stile di denominazione;Stili nomi;Regola di denominazione;Convenzioni di denominazione</target>
<note>Naming Style options page keywords</note>
</trans-unit>
<trans-unit id="111">
<source>General</source>
<target state="translated">Generale</target>
<note>"General" node under Tools >Options >Basic editor >Code Style.</note>
</trans-unit>
<trans-unit id="112">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note />
</trans-unit>
<trans-unit id="312">
<source>Change completion list settings;Pre-select most recently used member</source>
<target state="translated">Modifica impostazioni dell'elenco di completamento;Preseleziona membri usati di recente</target>
<note>IntelliSense options page keywords</note>
</trans-unit>
<trans-unit id="114">
<source>Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source>
<target state="translated">Componenti di Visual Basic usati nell'IDE. A seconda del tipo e delle impostazioni del processo, è possibile che venga usata una versione diversa del compilatore.</target>
<note>Help > About</note>
</trans-unit>
<trans-unit id="113">
<source>Visual Basic Tools</source>
<target state="translated">Strumenti di Visual Basic</target>
<note>Help > About</note>
</trans-unit>
<trans-unit id="An_empty_Visual_Basic_script_file">
<source>An empty Visual Basic script file.</source>
<target state="translated">File script di Visual Basic vuoto.</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Script">
<source>Visual Basic Script</source>
<target state="translated">Script di Visual Basic</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../VSPackage.resx">
<body>
<trans-unit id="101">
<source>Visual Basic</source>
<target state="translated">Visual Basic</target>
<note>Used anywhere the string is needed (that is, everywhere.)</note>
</trans-unit>
<trans-unit id="1012">
<source>Visual Basic Editor with Encoding</source>
<target state="translated">Visual Basic Editor con codifica</target>
<note />
</trans-unit>
<trans-unit id="1013">
<source>Visual Basic Editor</source>
<target state="translated">Visual Basic Editor</target>
<note />
</trans-unit>
<trans-unit id="10160">
<source>Underline reassigned variables;Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme;Inheritance Margin;Import Directives;</source>
<target state="needs-review-translation">Visualizza suggerimenti inline;Inserimento automatico di costrutti End;Modifica impostazioni di riformattazione;Modifica modalità struttura;Inserimento automatico di membri Interface e MustOverride;Mostra o nascondi separatori di riga routine;Attiva o disattiva i suggerimenti per la correzione degli errori;Attiva o disattiva l'evidenziazione di riferimenti e parole chiave;Regex;Colora espressioni regolari;Evidenzia i componenti correlati sotto il cursore;Segnala espressioni regolari non valide;regex;espressione regolare;Usa colori migliorati;Combinazione colori editor;</target>
<note>Advanced options page keywords</note>
</trans-unit>
<trans-unit id="102">
<source>Advanced</source>
<target state="translated">Avanzate</target>
<note>"Advanced" node under Tools >Options, Basic editor.</note>
</trans-unit>
<trans-unit id="103">
<source>Basic</source>
<target state="translated">Di base</target>
<note>"Basic" node in profile Import/Export.</note>
</trans-unit>
<trans-unit id="104">
<source>Basic Editor</source>
<target state="translated">Basic Editor</target>
<note>"Basic Editor" node in profile Import/Export.</note>
</trans-unit>
<trans-unit id="105">
<source>Options that control general editor features including Intellisense statement completion, line number display, and single-click URL navigation.</source>
<target state="translated">Opzioni che controllano le funzionalità generiche dell'editor, tra cui il completamento Intellisense delle istruzioni, la visualizzazione del numero di riga e l'apertura di URL con clic singolo.</target>
<note>"Basic" node help text in profile Import/Export.</note>
</trans-unit>
<trans-unit id="106">
<source>Options that control Visual Basic editor features including automatic insertion of end constructs, procedure line separators, and automatic code formatting.</source>
<target state="translated">Opzioni che controllano le funzionalità di Visual Basic Editor, tra cui l'inserimento automatico di costrutti End, i separatori di riga routine e la formattazione automatica del codice.</target>
<note>"Basic Editor" node help text in profile Import/Export.</note>
</trans-unit>
<trans-unit id="107">
<source>Optimizes the environment so you can focus on building world-class applications. This collection of settings contains customizations to the window layout, command menus and keyboard shortcuts to make common Visual Basic commands more accessible.</source>
<target state="translated">Ottimizza l'ambiente in modo da favorire la compilazione di applicazioni di qualità elevata. Questa raccolta di impostazioni contiene personalizzazioni relative a layout della finestra, menu dei comandi e tasti di scelta rapida per rendere più accessibili i comandi più usati di Visual Basic.</target>
<note>Profile description in profile Reset All Settings.</note>
</trans-unit>
<trans-unit id="108">
<source>Microsoft Visual Basic</source>
<target state="translated">Microsoft Visual Basic</target>
<note>Used for String in Tools > Options, Text Editor, File Extensions</note>
</trans-unit>
<trans-unit id="109">
<source>Code Style</source>
<target state="translated">Stile codice</target>
<note>"Code Style" category node under Tools >Options, Basic editor.</note>
</trans-unit>
<trans-unit id="10161">
<source>Qualify with Me;Prefer intrinsic types;Style;Code Style</source>
<target state="translated">Qualifica con utente;Preferisci tipi intrinseci;Stile;Stile codice</target>
<note>Code Style options page keywords</note>
</trans-unit>
<trans-unit id="110">
<source>Naming</source>
<target state="translated">Denominazione</target>
<note>"Naming Style" node under Tools >Options > Basic editor >Code Style.</note>
</trans-unit>
<trans-unit id="10162">
<source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source>
<target state="translated">Stile di denominazione;Stili nomi;Regola di denominazione;Convenzioni di denominazione</target>
<note>Naming Style options page keywords</note>
</trans-unit>
<trans-unit id="111">
<source>General</source>
<target state="translated">Generale</target>
<note>"General" node under Tools >Options >Basic editor >Code Style.</note>
</trans-unit>
<trans-unit id="112">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note />
</trans-unit>
<trans-unit id="312">
<source>Change completion list settings;Pre-select most recently used member</source>
<target state="translated">Modifica impostazioni dell'elenco di completamento;Preseleziona membri usati di recente</target>
<note>IntelliSense options page keywords</note>
</trans-unit>
<trans-unit id="114">
<source>Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source>
<target state="translated">Componenti di Visual Basic usati nell'IDE. A seconda del tipo e delle impostazioni del processo, è possibile che venga usata una versione diversa del compilatore.</target>
<note>Help > About</note>
</trans-unit>
<trans-unit id="113">
<source>Visual Basic Tools</source>
<target state="translated">Strumenti di Visual Basic</target>
<note>Help > About</note>
</trans-unit>
<trans-unit id="An_empty_Visual_Basic_script_file">
<source>An empty Visual Basic script file.</source>
<target state="translated">File script di Visual Basic vuoto.</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Script">
<source>Visual Basic Script</source>
<target state="translated">Script di Visual Basic</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 56,034 | Remove experimental suffix for inheritance margin | Cosifne | "2021-08-31T18:33:05Z" | "2021-08-31T20:48:02Z" | d471af61946b3709c65f63f9bfd9e331f5cde422 | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | Remove experimental suffix for inheritance margin. | ./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationAbstractMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal abstract class CodeGenerationAbstractMethodSymbol : CodeGenerationSymbol, IMethodSymbol
{
public new IMethodSymbol OriginalDefinition { get; protected set; }
private readonly ImmutableArray<AttributeData> _returnTypeAttributes;
public virtual ImmutableArray<AttributeData> GetReturnTypeAttributes()
=> _returnTypeAttributes;
protected CodeGenerationAbstractMethodSymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
Accessibility declaredAccessibility,
DeclarationModifiers modifiers,
string name,
ImmutableArray<AttributeData> returnTypeAttributes,
string documentationCommentXml = null)
: base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name, documentationCommentXml)
{
_returnTypeAttributes = returnTypeAttributes.NullToEmpty();
}
public abstract int Arity { get; }
public abstract System.Reflection.MethodImplAttributes MethodImplementationFlags { get; }
public abstract bool ReturnsVoid { get; }
public abstract bool ReturnsByRef { get; }
public abstract bool ReturnsByRefReadonly { get; }
public abstract RefKind RefKind { get; }
public abstract ITypeSymbol ReturnType { get; }
public abstract ImmutableArray<ITypeSymbol> TypeArguments { get; }
public abstract ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
public abstract ImmutableArray<IParameterSymbol> Parameters { get; }
public abstract IMethodSymbol ConstructedFrom { get; }
public abstract bool IsReadOnly { get; }
public abstract bool IsInitOnly { get; }
public abstract IMethodSymbol OverriddenMethod { get; }
public abstract IMethodSymbol ReducedFrom { get; }
public abstract ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
public abstract IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType);
public abstract ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
public abstract IMethodSymbol PartialDefinitionPart { get; }
public abstract IMethodSymbol PartialImplementationPart { get; }
public abstract bool IsPartialDefinition { get; }
public NullableAnnotation ReceiverNullableAnnotation => ReceiverType.NullableAnnotation;
public NullableAnnotation ReturnNullableAnnotation => ReturnType.NullableAnnotation;
public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => TypeArguments.SelectAsArray(a => a.NullableAnnotation);
public virtual ITypeSymbol ReceiverType => this.ContainingType;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitMethod(this);
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> visitor.VisitMethod(this);
public virtual MethodKind MethodKind => MethodKind.Ordinary;
public override SymbolKind Kind => SymbolKind.Method;
public virtual bool IsGenericMethod => this.Arity > 0;
public virtual bool IsExtensionMethod => false;
public virtual bool IsAsync => this.Modifiers.IsAsync;
public virtual bool IsVararg => false;
public bool IsCheckedBuiltin => false;
public override ISymbol ContainingSymbol => this.ContainingType;
public virtual bool HidesBaseMethodsByName => false;
public ImmutableArray<CustomModifier> RefCustomModifiers
=> ImmutableArray.Create<CustomModifier>();
public virtual ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
=> ImmutableArray.Create<CustomModifier>();
public virtual ISymbol AssociatedSymbol => null;
public INamedTypeSymbol AssociatedAnonymousDelegate => null;
public bool IsConditional => false;
public SignatureCallingConvention CallingConvention => SignatureCallingConvention.Default;
public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => ImmutableArray<INamedTypeSymbol>.Empty;
public IMethodSymbol Construct(params ITypeSymbol[] typeArguments)
=> new CodeGenerationConstructedMethodSymbol(this, typeArguments.ToImmutableArray());
public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations)
=> new CodeGenerationConstructedMethodSymbol(this, typeArguments);
public DllImportData GetDllImportData()
=> null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal abstract class CodeGenerationAbstractMethodSymbol : CodeGenerationSymbol, IMethodSymbol
{
public new IMethodSymbol OriginalDefinition { get; protected set; }
private readonly ImmutableArray<AttributeData> _returnTypeAttributes;
public virtual ImmutableArray<AttributeData> GetReturnTypeAttributes()
=> _returnTypeAttributes;
protected CodeGenerationAbstractMethodSymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
Accessibility declaredAccessibility,
DeclarationModifiers modifiers,
string name,
ImmutableArray<AttributeData> returnTypeAttributes,
string documentationCommentXml = null)
: base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name, documentationCommentXml)
{
_returnTypeAttributes = returnTypeAttributes.NullToEmpty();
}
public abstract int Arity { get; }
public abstract System.Reflection.MethodImplAttributes MethodImplementationFlags { get; }
public abstract bool ReturnsVoid { get; }
public abstract bool ReturnsByRef { get; }
public abstract bool ReturnsByRefReadonly { get; }
public abstract RefKind RefKind { get; }
public abstract ITypeSymbol ReturnType { get; }
public abstract ImmutableArray<ITypeSymbol> TypeArguments { get; }
public abstract ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
public abstract ImmutableArray<IParameterSymbol> Parameters { get; }
public abstract IMethodSymbol ConstructedFrom { get; }
public abstract bool IsReadOnly { get; }
public abstract bool IsInitOnly { get; }
public abstract IMethodSymbol OverriddenMethod { get; }
public abstract IMethodSymbol ReducedFrom { get; }
public abstract ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
public abstract IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType);
public abstract ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
public abstract IMethodSymbol PartialDefinitionPart { get; }
public abstract IMethodSymbol PartialImplementationPart { get; }
public abstract bool IsPartialDefinition { get; }
public NullableAnnotation ReceiverNullableAnnotation => ReceiverType.NullableAnnotation;
public NullableAnnotation ReturnNullableAnnotation => ReturnType.NullableAnnotation;
public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => TypeArguments.SelectAsArray(a => a.NullableAnnotation);
public virtual ITypeSymbol ReceiverType => this.ContainingType;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitMethod(this);
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> visitor.VisitMethod(this);
public virtual MethodKind MethodKind => MethodKind.Ordinary;
public override SymbolKind Kind => SymbolKind.Method;
public virtual bool IsGenericMethod => this.Arity > 0;
public virtual bool IsExtensionMethod => false;
public virtual bool IsAsync => this.Modifiers.IsAsync;
public virtual bool IsVararg => false;
public bool IsCheckedBuiltin => false;
public override ISymbol ContainingSymbol => this.ContainingType;
public virtual bool HidesBaseMethodsByName => false;
public ImmutableArray<CustomModifier> RefCustomModifiers
=> ImmutableArray.Create<CustomModifier>();
public virtual ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
=> ImmutableArray.Create<CustomModifier>();
public virtual ISymbol AssociatedSymbol => null;
public INamedTypeSymbol AssociatedAnonymousDelegate => null;
public bool IsConditional => false;
public SignatureCallingConvention CallingConvention => SignatureCallingConvention.Default;
public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => ImmutableArray<INamedTypeSymbol>.Empty;
public IMethodSymbol Construct(params ITypeSymbol[] typeArguments)
=> new CodeGenerationConstructedMethodSymbol(this, typeArguments.ToImmutableArray());
public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations)
=> new CodeGenerationConstructedMethodSymbol(this, typeArguments);
public DllImportData GetDllImportData()
=> null;
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.