repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocInitializerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.StackAllocInitializer)]
public class StackAllocInitializerTests : CompilingTestBase
{
[Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")]
public void RestrictedTypesAllowedInStackalloc()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
public ref struct RefS { }
public ref struct RefG<T> { public T field; }
class C
{
unsafe void M()
{
var x1 = stackalloc RefS[10];
var x2 = stackalloc RefG<string>[10];
var x3 = stackalloc RefG<int>[10];
var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference
var x5 = stackalloc System.ArgIterator[10];
var x6 = stackalloc System.RuntimeArgumentHandle[10];
var y1 = new RefS[10];
var y2 = new RefG<string>[10];
var y3 = new RefG<int>[10];
var y4 = new System.TypedReference[10];
var y5 = new System.ArgIterator[10];
var y6 = new System.RuntimeArgumentHandle[10];
RefS[] z1 = null;
RefG<string>[] z2 = null;
RefG<int>[] z3 = null;
System.TypedReference[] z4 = null;
System.ArgIterator[] z5 = null;
System.RuntimeArgumentHandle[] z6 = null;
_ = z1;
_ = z2;
_ = z3;
_ = z4;
_ = z5;
_ = z6;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>')
// var x2 = stackalloc RefG<string>[10];
Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29),
// (16,22): error CS0611: Array elements cannot be of type 'RefS'
// var y1 = new RefS[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22),
// (17,22): error CS0611: Array elements cannot be of type 'RefG<string>'
// var y2 = new RefG<string>[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22),
// (18,22): error CS0611: Array elements cannot be of type 'RefG<int>'
// var y3 = new RefG<int>[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22),
// (19,22): error CS0611: Array elements cannot be of type 'TypedReference'
// var y4 = new System.TypedReference[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22),
// (20,22): error CS0611: Array elements cannot be of type 'ArgIterator'
// var y5 = new System.ArgIterator[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22),
// (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle'
// var y6 = new System.RuntimeArgumentHandle[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22),
// (23,9): error CS0611: Array elements cannot be of type 'RefS'
// RefS[] z1 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9),
// (24,9): error CS0611: Array elements cannot be of type 'RefG<string>'
// RefG<string>[] z2 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9),
// (25,9): error CS0611: Array elements cannot be of type 'RefG<int>'
// RefG<int>[] z3 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9),
// (26,9): error CS0611: Array elements cannot be of type 'TypedReference'
// System.TypedReference[] z4 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9),
// (27,9): error CS0611: Array elements cannot be of type 'ArgIterator'
// System.ArgIterator[] z5 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9),
// (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle'
// System.RuntimeArgumentHandle[] z6 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9)
);
}
[Fact]
public void NoBestType_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
struct A {}
struct B {}
void Method(dynamic d, RefStruct r)
{
var p0 = stackalloc[] { new A(), new B() };
var p1 = stackalloc[] { };
var p2 = stackalloc[] { VoidMethod() };
var p3 = stackalloc[] { null };
var p4 = stackalloc[] { (1, null) };
var p5 = stackalloc[] { () => { } };
var p6 = stackalloc[] { new {} , new { i = 0 } };
var p7 = stackalloc[] { d };
var p8 = stackalloc[] { _ };
}
public void VoidMethod() {}
}
namespace System {
public struct ValueTuple<T1, T2> {
public ValueTuple(T1 a, T2 b) => throw null;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// void Method(dynamic d, RefStruct r)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28),
// (9,18): error CS0826: No best type found for implicitly-typed array
// var p0 = stackalloc[] { new A(), new B() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18),
// (10,18): error CS0826: No best type found for implicitly-typed array
// var p1 = stackalloc[] { };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18),
// (11,18): error CS0826: No best type found for implicitly-typed array
// var p2 = stackalloc[] { VoidMethod() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18),
// (12,18): error CS0826: No best type found for implicitly-typed array
// var p3 = stackalloc[] { null };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18),
// (13,18): error CS0826: No best type found for implicitly-typed array
// var p4 = stackalloc[] { (1, null) };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18),
// (14,18): error CS0826: No best type found for implicitly-typed array
// var p5 = stackalloc[] { () => { } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18),
// (15,18): error CS0826: No best type found for implicitly-typed array
// var p6 = stackalloc[] { new {} , new { i = 0 } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18),
// (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var p7 = stackalloc[] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18),
// (17,33): error CS0103: The name '_' does not exist in the current context
// var p8 = stackalloc[] { _ };
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33)
);
}
[Fact]
public void NoBestType_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
struct A {}
struct B {}
void Method(dynamic d, bool c)
{
var p0 = c ? default : stackalloc[] { new A(), new B() };
var p1 = c ? default : stackalloc[] { };
var p2 = c ? default : stackalloc[] { VoidMethod() };
var p3 = c ? default : stackalloc[] { null };
var p4 = c ? default : stackalloc[] { (1, null) };
var p5 = c ? default : stackalloc[] { () => { } };
var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } };
var p7 = c ? default : stackalloc[] { d };
var p8 = c ? default : stackalloc[] { _ };
}
public void VoidMethod() {}
}
namespace System {
public struct ValueTuple<T1, T2> {
public ValueTuple(T1 a, T2 b) => throw null;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (9,32): error CS0826: No best type found for implicitly-typed array
// var p0 = c ? default : stackalloc[] { new A(), new B() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32),
// (10,32): error CS0826: No best type found for implicitly-typed array
// var p1 = c ? default : stackalloc[] { };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32),
// (11,32): error CS0826: No best type found for implicitly-typed array
// var p2 = c ? default : stackalloc[] { VoidMethod() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32),
// (12,32): error CS0826: No best type found for implicitly-typed array
// var p3 = c ? default : stackalloc[] { null };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32),
// (13,32): error CS0826: No best type found for implicitly-typed array
// var p4 = c ? default : stackalloc[] { (1, null) };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32),
// (14,32): error CS0826: No best type found for implicitly-typed array
// var p5 = c ? default : stackalloc[] { () => { } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32),
// (15,32): error CS0826: No best type found for implicitly-typed array
// var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32),
// (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var p7 = c ? default : stackalloc[] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32),
// (17,47): error CS0103: The name '_' does not exist in the current context
// var p8 = c ? default : stackalloc[] { _ };
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47)
);
}
[Fact]
public void InitializeWithSelf_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void Method1()
{
var obj1 = stackalloc int[1] { obj1 };
var obj2 = stackalloc int[ ] { obj2 };
var obj3 = stackalloc [ ] { obj3 };
}
void Method2()
{
var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[1] { obj1 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40),
// (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40),
// (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40),
// (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40),
// (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50),
// (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40),
// (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50),
// (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40),
// (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50)
);
}
[Fact]
public void InitializeWithSelf_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void Method1(bool c)
{
var obj1 = c ? default : stackalloc int[1] { obj1 };
var obj2 = c ? default : stackalloc int[ ] { obj2 };
var obj3 = c ? default : stackalloc [ ] { obj3 };
}
void Method2(bool c)
{
var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[1] { obj1 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54),
// (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54),
// (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54),
// (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54),
// (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64),
// (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54),
// (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64),
// (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54),
// (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64)
);
}
[Fact]
public void BadBestType_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
ref struct S {}
void Method1(S s)
{
var obj1 = stackalloc[] { """" };
var obj2 = stackalloc[] { new {} };
var obj3 = stackalloc[] { s }; // OK
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// var obj1 = stackalloc[] { "" };
Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20),
// (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var obj2 = stackalloc[] { new {} };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.String", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
}
[Fact]
public void BadBestType_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
ref struct S {}
void Method1(S s, bool c)
{
var obj1 = c ? default : stackalloc[] { """" };
var obj2 = c ? default : stackalloc[] { new {} };
var obj3 = c ? default : stackalloc[] { s };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// var obj1 = c ? default : stackalloc[] { "" };
Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34),
// (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var obj2 = c ? default : stackalloc[] { new {} };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34),
// (9,34): error CS0306: The type 'Test.S' may not be used as a type argument
// var obj3 = c ? default : stackalloc[] { s };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.String", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
}
[Fact]
public void TestFor_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
static void Method1()
{
int i = 0;
for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method2()
{
int i = 0;
for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method3()
{
int i = 0;
for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
public static void Main()
{
Method1();
Method2();
Method3();
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails);
}
[Fact]
public void TestFor_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
static void Method1()
{
int i = 0;
for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method2()
{
int i = 0;
for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method3()
{
int i = 0;
for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
public static void Main()
{
Method1();
Method2();
Method3();
}
}", TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void TestForTernary()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
class Test
{
static void Method1(bool b)
{
for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {}
for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {}
for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {}
}
}", TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[Fact]
public void TestLock()
{
var source = @"
class Test
{
static void Method1()
{
lock (stackalloc int[3] { 1, 2, 3 }) {}
lock (stackalloc int[ ] { 1, 2, 3 }) {}
lock (stackalloc [ ] { 1, 2, 3 }) {}
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15),
// (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15),
// (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15),
// (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15),
// (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15),
// (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15),
// (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15),
// (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15)
);
}
[Fact]
public void TestSelect()
{
var source = @"
using System.Linq;
class Test
{
static void Method1(int[] array)
{
var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44),
// (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44),
// (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37),
// (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37),
// (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37)
);
}
[Fact]
public void TestLet()
{
var source = @"
using System.Linq;
class Test
{
static void Method1(int[] array)
{
var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45),
// (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45),
// (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75),
// (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75),
// (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75)
);
}
[Fact]
public void TestAwait_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System.Threading.Tasks;
unsafe class Test
{
async void M()
{
var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,32): error CS4004: Cannot await in an unsafe context
// var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32),
// (7,60): error CS4004: Cannot await in an unsafe context
// var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60)
);
}
[Fact]
public void TestAwait_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
using System.Threading.Tasks;
class Test
{
async void M()
{
Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (8,38): error CS0150: A constant value is expected
// Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38),
// (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions.
// Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9)
);
}
[Fact]
public void TestSelfInSize()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void M()
{
var x = stackalloc int[x] { };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,32): error CS0841: Cannot use local variable 'x' before it is declared
// var x = stackalloc int[x] { };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32)
);
}
[Fact]
public void WrongLength()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[10] { };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,20): error CS0847: An array initializer of length '10' is expected
// var obj1 = stackalloc int[10] { };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20)
);
}
[Fact]
public void NoInit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[];
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,34): error CS1586: Array creation must have array size or array initializer
// var obj1 = stackalloc int[];
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34)
);
}
[Fact]
public void NestedInit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[1] { { 42 } };
var obj2 = stackalloc int[ ] { { 42 } };
var obj3 = stackalloc [ ] { { 42 } };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj1 = stackalloc int[1] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40),
// (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj2 = stackalloc int[ ] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40),
// (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj3 = stackalloc [ ] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40)
);
}
[Fact]
public void AsStatement()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
stackalloc[] {1};
stackalloc int[] {1};
stackalloc int[1] {1};
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc[] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9),
// (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc int[] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9),
// (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc int[1] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9)
);
}
[Fact]
public void BadRank()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[][] { 1 };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// var obj1 = stackalloc int[][] { 1 };
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31),
// (6,31): error CS1575: A stackalloc expression requires [] after type
// var obj1 = stackalloc int[][] { 1 };
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31)
);
}
[Fact]
public void BadDimension()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[,] { 1 };
var obj2 = stackalloc [,] { 1 };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,35): error CS8381: "Invalid rank specifier: expected ']'
// var obj2 = stackalloc [,] { 1 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35),
// (6,31): error CS1575: A stackalloc expression requires [] after type
// var obj1 = stackalloc int[,] { 1 };
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31)
);
}
[Fact]
public void TestFlowPass1()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
int i, j, k;
var obj1 = stackalloc int [1] { i = 1 };
var obj2 = stackalloc int [ ] { j = 2 };
var obj3 = stackalloc [ ] { k = 3 };
Console.Write(i);
Console.Write(j);
Console.Write(k);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestFlowPass2()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public static void Main()
{
int i, j, k;
var obj1 = stackalloc int [1] { i };
var obj2 = stackalloc int [ ] { j };
var obj3 = stackalloc [ ] { k };
}
}", TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (7,41): error CS0165: Use of unassigned local variable 'i'
// var obj1 = stackalloc int [1] { i };
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41),
// (8,41): error CS0165: Use of unassigned local variable 'j'
// var obj2 = stackalloc int [ ] { j };
Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41),
// (9,41): error CS0165: Use of unassigned local variable 'k'
// var obj3 = stackalloc [ ] { k };
Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41)
);
}
[Fact]
public void ConversionFromPointerStackAlloc_UserDefined_Implicit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
Test obj1 = stackalloc int[3] { 1, 2, 3 };
var obj2 = stackalloc int[3] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[3] { 1, 2, 3 };
int* obj4 = stackalloc int[3] { 1, 2, 3 };
double* obj5 = stackalloc int[3] { 1, 2, 3 };
}
public void Method2()
{
Test obj1 = stackalloc int[] { 1, 2, 3 };
var obj2 = stackalloc int[] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[] { 1, 2, 3 };
int* obj4 = stackalloc int[] { 1, 2, 3 };
double* obj5 = stackalloc int[] { 1, 2, 3 };
}
public void Method3()
{
Test obj1 = stackalloc[] { 1, 2, 3 };
var obj2 = stackalloc[] { 1, 2, 3 };
Span<int> obj3 = stackalloc[] { 1, 2, 3 };
int* obj4 = stackalloc[] { 1, 2, 3 };
double* obj5 = stackalloc[] { 1, 2, 3 };
}
public static implicit operator Test(int* value)
{
return default(Test);
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24),
// (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24),
// (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
Assert.Equal(15, variables.Count());
for (int i = 0; i < 15; i += 5)
{
var obj1 = variables.ElementAt(i);
Assert.Equal("obj1", obj1.Identifier.Text);
var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType);
Assert.Equal("Test", obj1Value.ConvertedType.Name);
Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind);
var obj2 = variables.ElementAt(i + 1);
Assert.Equal("obj2", obj2.Identifier.Text);
var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind);
var obj3 = variables.ElementAt(i + 2);
Assert.Equal("obj3", obj3.Identifier.Text);
var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value);
Assert.Equal("Span", obj3Value.Type.Name);
Assert.Equal("Span", obj3Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind);
var obj4 = variables.ElementAt(i + 3);
Assert.Equal("obj4", obj4.Identifier.Text);
var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind);
var obj5 = variables.ElementAt(i + 4);
Assert.Equal("obj5", obj5.Identifier.Text);
var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind);
}
}
[Fact]
public void ConversionFromPointerStackAlloc_UserDefined_Explicit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 };
var obj2 = stackalloc int[3] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[3] { 1, 2, 3 };
int* obj4 = stackalloc int[3] { 1, 2, 3 };
double* obj5 = stackalloc int[3] { 1, 2, 3 };
}
public void Method2()
{
Test obj1 = (Test)stackalloc int[] { 1, 2, 3 };
var obj2 = stackalloc int[] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[] { 1, 2, 3 };
int* obj4 = stackalloc int[] { 1, 2, 3 };
double* obj5 = stackalloc int[] { 1, 2, 3 };
}
public void Method3()
{
Test obj1 = (Test)stackalloc [] { 1, 2, 3 };
var obj2 = stackalloc[] { 1, 2, 3 };
Span<int> obj3 = stackalloc [] { 1, 2, 3 };
int* obj4 = stackalloc[] { 1, 2, 3 };
double* obj5 = stackalloc[] { 1, 2, 3 };
}
public static explicit operator Test(Span<int> value)
{
return default(Test);
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24),
// (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24),
// (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
Assert.Equal(15, variables.Count());
for (int i = 0; i < 15; i += 5)
{
var obj1 = variables.ElementAt(i);
Assert.Equal("obj1", obj1.Identifier.Text);
Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind());
var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression);
Assert.Equal("Span", obj1Value.Type.Name);
Assert.Equal("Span", obj1Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind);
var obj2 = variables.ElementAt(i + 1);
Assert.Equal("obj2", obj2.Identifier.Text);
var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind);
var obj3 = variables.ElementAt(i + 2);
Assert.Equal("obj3", obj3.Identifier.Text);
var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value);
Assert.Equal("Span", obj3Value.Type.Name);
Assert.Equal("Span", obj3Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind);
var obj4 = variables.ElementAt(i + 3);
Assert.Equal("obj4", obj4.Identifier.Text);
var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind);
var obj5 = variables.ElementAt(i + 4);
Assert.Equal("obj5", obj5.Identifier.Text);
var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind);
}
}
[Fact]
public void ConversionError()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void Method1()
{
double x = stackalloc int[3] { 1, 2, 3 }; // implicit
short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit
}
void Method2()
{
double x = stackalloc int[] { 1, 2, 3 }; // implicit
short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit
}
void Method3()
{
double x = stackalloc[] { 1, 2, 3 }; // implicit
short y = (short)stackalloc[] { 1, 2, 3 }; // explicit
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc int[3] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19),
// (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc int[] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20),
// (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19),
// (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc[] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20),
// (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc[] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19)
);
}
[Fact]
public void MissingSpanType()
{
CreateCompilation(@"
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
}
}").VerifyDiagnostics(
// (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9),
// (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24),
// (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9),
// (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24),
// (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9),
// (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24)
);
}
[Fact]
public void MissingSpanConstructor()
{
CreateCompilation(@"
namespace System
{
ref struct Span<T>
{
}
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
}
}
}").VerifyEmitDiagnostics(
// (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28),
// (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28),
// (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28)
);
}
[Fact]
public void ConditionalExpressionOnSpan_BothStackallocSpans()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_Convertible()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_NoCast()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59),
// (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59),
// (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59)
);
}
[Fact]
public void ConditionalExpressionOnSpan_CompatibleTypes()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1;
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2;
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3;
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_IncompatibleTypes()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<short> a = stackalloc short [10];
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a;
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a;
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a;
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18),
// (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18),
// (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18)
);
}
[Fact]
public void ConditionalExpressionOnSpan_Nested()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
bool N() => true;
void M()
{
var x = N()
? N()
? stackalloc int[1] { 42 }
: stackalloc int[ ] { 42 }
: N()
? stackalloc[] { 42 }
: N()
? stackalloc int[2]
: stackalloc int[3];
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void BooleanOperatorOnSpan_NoTargetTyping()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void M()
{
if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { }
if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { }
if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { }
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13),
// (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13),
// (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13)
);
}
[Fact]
public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions()
{
var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7);
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<int> x1 = stackalloc int [3] { 1, 2, 3 };
Span<int> x2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> x3 = stackalloc [ ] { 1, 2, 3 };
}
}", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics(
// (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24),
// (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24),
// (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24)
);
}
[Fact]
public void StackAllocSyntaxProducesUnsafeErrorInSafeCode()
{
CreateCompilation(@"
class Test
{
void M()
{
var x1 = stackalloc int [3] { 1, 2, 3 };
var x2 = stackalloc int [ ] { 1, 2, 3 };
var x3 = stackalloc [ ] { 1, 2, 3 };
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18),
// (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18),
// (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18)
);
}
[Fact]
public void StackAllocInUsing1()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
using (var v1 = stackalloc int [3] { 1, 2, 3 })
using (var v2 = stackalloc int [ ] { 1, 2, 3 })
using (var v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16),
// (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16),
// (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16)
);
}
[Fact]
public void StackAllocInUsing2()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 })
using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 })
using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40),
// (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40),
// (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40)
);
}
[Fact]
public void StackAllocInFixed()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
fixed (int* v1 = stackalloc int [3] { 1, 2, 3 })
fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 })
fixed (int* v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26),
// (7,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26),
// (8,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26)
);
}
[Fact]
public void ConstStackAllocExpression()
{
var test = @"
unsafe public class Test
{
void M()
{
const int* p1 = stackalloc int [3] { 1, 2, 3 };
const int* p2 = stackalloc int [ ] { 1, 2, 3 };
const int* p3 = stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (6,15): error CS0283: The type 'int*' cannot be declared const
// const int* p1 = stackalloc int[1] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15),
// (7,15): error CS0283: The type 'int*' cannot be declared const
// const int* p2 = stackalloc int[] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15),
// (8,15): error CS0283: The type 'int*' cannot be declared const
// const int* p3 = stackalloc [] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15)
);
}
[Fact]
public void RefStackAllocAssignment_ValueToRef()
{
var test = @"
using System;
public class Test
{
void M()
{
ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (7,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23),
// (7,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28),
// (8,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23),
// (8,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28),
// (9,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23),
// (9,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28)
);
}
[Fact]
public void RefStackAllocAssignment_RefToRef()
{
var test = @"
using System;
public class Test
{
void M()
{
ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 };
ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 };
ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (7,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32),
// (8,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32),
// (9,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32)
);
}
[Fact]
public void InvalidPositionForStackAllocSpan()
{
var test = @"
using System;
public class Test
{
void M()
{
N(stackalloc int [3] { 1, 2, 3 });
N(stackalloc int [ ] { 1, 2, 3 });
N(stackalloc [ ] { 1, 2, 3 });
}
void N(Span<int> span)
{
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11),
// (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11),
// (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11)
);
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics(
);
}
[Fact]
public void CannotDotIntoStackAllocExpression()
{
var test = @"
public class Test
{
void M()
{
int length1 = (stackalloc int [3] { 1, 2, 3 }).Length;
int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length;
int length3 = (stackalloc [ ] { 1, 2, 3 }).Length;
int length4 = stackalloc int [3] { 1, 2, 3 }.Length;
int length5 = stackalloc int [ ] { 1, 2, 3 }.Length;
int length6 = stackalloc [ ] { 1, 2, 3 }.Length;
}
}
";
CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length1 = (stackalloc int [3] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24),
// (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24),
// (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length3 = (stackalloc [ ] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24),
// (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length4 = stackalloc int [3] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23),
// (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length5 = stackalloc int [ ] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23),
// (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length6 = stackalloc [ ] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23)
);
CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact]
public void OverloadResolution_Fail()
{
var test = @"
using System;
unsafe public class Test
{
static void Main()
{
Invoke(stackalloc int [3] { 1, 2, 3 });
Invoke(stackalloc int [ ] { 1, 2, 3 });
Invoke(stackalloc [ ] { 1, 2, 3 });
}
static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan"");
static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan"");
static void Invoke(int* intPointer) => Console.WriteLine(""intPointer"");
static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer"");
}
";
CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16),
// (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16),
// (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16)
);
CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics(
// (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16),
// (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16),
// (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16)
);
}
[Fact]
public void StackAllocWithDynamic()
{
CreateCompilation(@"
class Program
{
static void Main()
{
dynamic d = 1;
var d1 = stackalloc dynamic [3] { d };
var d2 = stackalloc dynamic [ ] { d };
var d3 = stackalloc [ ] { d };
}
}").VerifyDiagnostics(
// (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29),
// (7,18): error CS0847: An array initializer of length '3' is expected
// var d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18),
// (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d2 = stackalloc dynamic [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29),
// (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18),
// (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18)
);
}
[Fact]
public void StackAllocWithDynamicSpan()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Program
{
static void Main()
{
dynamic d = 1;
Span<dynamic> d1 = stackalloc dynamic [3] { d };
Span<dynamic> d2 = stackalloc dynamic [ ] { d };
Span<dynamic> d3 = stackalloc [ ] { d };
}
}").VerifyDiagnostics(
// (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39),
// (8,28): error CS0847: An array initializer of length '3' is expected
// Span<dynamic> d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28),
// (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d2 = stackalloc dynamic [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39),
// (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28)
);
}
[Fact]
public void StackAllocAsArgument()
{
var source = @"
class Program
{
static void N(object p) { }
static void Main()
{
N(stackalloc int [3] { 1, 2, 3 });
N(stackalloc int [ ] { 1, 2, 3 });
N(stackalloc [ ] { 1, 2, 3 });
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11),
// (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11),
// (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11)
);
CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics(
// (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11),
// (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11),
// (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11)
);
}
[Fact]
public void StackAllocInParenthesis()
{
var source = @"
class Program
{
static void Main()
{
var x1 = (stackalloc int [3] { 1, 2, 3 });
var x2 = (stackalloc int [ ] { 1, 2, 3 });
var x3 = (stackalloc [ ] { 1, 2, 3 });
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = (stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19),
// (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = (stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19),
// (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = (stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19)
);
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
);
}
[Fact]
public void StackAllocInNullConditionalOperator()
{
var source = @"
class Program
{
static void Main()
{
var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18),
// (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52),
// (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18),
// (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52),
// (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18),
// (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52)
);
CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18),
// (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18),
// (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18)
);
}
[Fact]
public void StackAllocInCastAndConditionalOperator()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void Method()
{
Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 };
Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 };
Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 };
}
public static explicit operator Test(Span<int> value)
{
return new Test();
}
}", TestOptions.ReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ERR_StackallocInCatchFinally_Catch()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err11 = stackalloc int [3] { 1, 2, 3 };
int* err12 = stackalloc int [ ] { 1, 2, 3 };
int* err13 = stackalloc [ ] { 1, 2, 3 };
}
};
}
catch
{
int* err21 = stackalloc int [3] { 1, 2, 3 };
int* err22 = stackalloc int [ ] { 1, 2, 3 };
int* err23 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err31 = stackalloc int [3] { 1, 2, 3 };
int* err32 = stackalloc int [ ] { 1, 2, 3 };
int* err33 = stackalloc [ ] { 1, 2, 3 };
}
};
}
});
static int M(System.Action action)
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err41 = stackalloc int [3] { 1, 2, 3 };
int* err42 = stackalloc int [ ] { 1, 2, 3 };
int* err43 = stackalloc [ ] { 1, 2, 3 };
}
};
}
catch
{
int* err51 = stackalloc int [3] { 1, 2, 3 };
int* err52 = stackalloc int [ ] { 1, 2, 3 };
int* err53 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err61 = stackalloc int [3] { 1, 2, 3 };
int* err62 = stackalloc int [ ] { 1, 2, 3 };
int* err63 = stackalloc [ ] { 1, 2, 3 };
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (23,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err11 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34),
// (24,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err12 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34),
// (25,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err13 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34),
// (31,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err21 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26),
// (32,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err22 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26),
// (33,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err23 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26),
// (45,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err31 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34),
// (46,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err32 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34),
// (47,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err33 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34),
// (72,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err41 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34),
// (73,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err42 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34),
// (74,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err43 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34),
// (80,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err51 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26),
// (81,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err52 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26),
// (82,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err53 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26),
// (94,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err61 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34),
// (95,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err62 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34),
// (96,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err63 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34)
);
}
[Fact]
public void ERR_StackallocInCatchFinally_Finally()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err11 = stackalloc int [3] { 1, 2, 3 };
int* err12 = stackalloc int [ ] { 1, 2, 3 };
int* err13 = stackalloc [ ] { 1, 2, 3 };
}
};
}
finally
{
int* err21 = stackalloc int [3] { 1, 2, 3 };
int* err22 = stackalloc int [ ] { 1, 2, 3 };
int* err23 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err31 = stackalloc int [3] { 1, 2, 3 };
int* err32 = stackalloc int [ ] { 1, 2, 3 };
int* err33 = stackalloc [ ] { 1, 2, 3 };
}
};
}
});
static int M(System.Action action)
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err41 = stackalloc int [3] { 1, 2, 3 };
int* err42 = stackalloc int [ ] { 1, 2, 3 };
int* err43 = stackalloc [ ] { 1, 2, 3 };
}
};
}
finally
{
int* err51 = stackalloc int [3] { 1, 2, 3 };
int* err52 = stackalloc int [ ] { 1, 2, 3 };
int* err53 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err61 = stackalloc int [3] { 1, 2, 3 };
int* err62 = stackalloc int [ ] { 1, 2, 3 };
int* err63 = stackalloc [ ] { 1, 2, 3 };
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (23,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err11 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34),
// (24,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err12 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34),
// (25,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err13 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34),
// (31,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err21 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26),
// (32,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err22 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26),
// (33,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err23 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26),
// (45,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err31 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34),
// (46,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err32 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34),
// (47,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err33 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34),
// (72,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err41 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34),
// (73,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err42 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34),
// (74,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err43 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34),
// (80,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err51 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26),
// (81,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err52 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26),
// (82,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err53 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26),
// (94,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err61 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34),
// (95,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err62 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34),
// (96,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err63 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34)
);
}
[Fact]
public void StackAllocArrayCreationExpression_Symbols()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc double[2] { 1, 1.2 };
Span<double> obj2 = stackalloc double[2] { 1, 1.2 };
_ = stackalloc double[2] { 1, 1.2 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method
// _ = stackalloc double[2] { 1, 1.2 };
Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void ImplicitStackAllocArrayCreationExpression_Symbols()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc[] { 1, 1.2 };
Span<double> obj2 = stackalloc[] { 1, 1.2 };
_ = stackalloc[] { 1, 1.2 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method
// _ = stackalloc[] { 1, 1.2 };
Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void StackAllocArrayCreationExpression_Symbols_ErrorCase()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,41): error CS0150: A constant value is expected
// short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41),
// (8,46): error CS0150: A constant value is expected
// Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46),
// (7,42): error CS0165: Use of unassigned local variable 'obj1'
// short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42),
// (8,46): error CS0165: Use of unassigned local variable 'obj2'
// Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(2, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
double* obj1 = stackalloc[] { obj1[0], *obj1 };
Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,39): error CS0165: Use of unassigned local variable 'obj1'
// double* obj1 = stackalloc[] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39),
// (8,44): error CS0165: Use of unassigned local variable 'obj2'
// Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(2, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.StackAllocInitializer)]
public class StackAllocInitializerTests : CompilingTestBase
{
[Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")]
public void RestrictedTypesAllowedInStackalloc()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
public ref struct RefS { }
public ref struct RefG<T> { public T field; }
class C
{
unsafe void M()
{
var x1 = stackalloc RefS[10];
var x2 = stackalloc RefG<string>[10];
var x3 = stackalloc RefG<int>[10];
var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference
var x5 = stackalloc System.ArgIterator[10];
var x6 = stackalloc System.RuntimeArgumentHandle[10];
var y1 = new RefS[10];
var y2 = new RefG<string>[10];
var y3 = new RefG<int>[10];
var y4 = new System.TypedReference[10];
var y5 = new System.ArgIterator[10];
var y6 = new System.RuntimeArgumentHandle[10];
RefS[] z1 = null;
RefG<string>[] z2 = null;
RefG<int>[] z3 = null;
System.TypedReference[] z4 = null;
System.ArgIterator[] z5 = null;
System.RuntimeArgumentHandle[] z6 = null;
_ = z1;
_ = z2;
_ = z3;
_ = z4;
_ = z5;
_ = z6;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>')
// var x2 = stackalloc RefG<string>[10];
Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29),
// (16,22): error CS0611: Array elements cannot be of type 'RefS'
// var y1 = new RefS[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22),
// (17,22): error CS0611: Array elements cannot be of type 'RefG<string>'
// var y2 = new RefG<string>[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22),
// (18,22): error CS0611: Array elements cannot be of type 'RefG<int>'
// var y3 = new RefG<int>[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22),
// (19,22): error CS0611: Array elements cannot be of type 'TypedReference'
// var y4 = new System.TypedReference[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22),
// (20,22): error CS0611: Array elements cannot be of type 'ArgIterator'
// var y5 = new System.ArgIterator[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22),
// (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle'
// var y6 = new System.RuntimeArgumentHandle[10];
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22),
// (23,9): error CS0611: Array elements cannot be of type 'RefS'
// RefS[] z1 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9),
// (24,9): error CS0611: Array elements cannot be of type 'RefG<string>'
// RefG<string>[] z2 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9),
// (25,9): error CS0611: Array elements cannot be of type 'RefG<int>'
// RefG<int>[] z3 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9),
// (26,9): error CS0611: Array elements cannot be of type 'TypedReference'
// System.TypedReference[] z4 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9),
// (27,9): error CS0611: Array elements cannot be of type 'ArgIterator'
// System.ArgIterator[] z5 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9),
// (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle'
// System.RuntimeArgumentHandle[] z6 = null;
Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9)
);
}
[Fact]
public void NoBestType_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
struct A {}
struct B {}
void Method(dynamic d, RefStruct r)
{
var p0 = stackalloc[] { new A(), new B() };
var p1 = stackalloc[] { };
var p2 = stackalloc[] { VoidMethod() };
var p3 = stackalloc[] { null };
var p4 = stackalloc[] { (1, null) };
var p5 = stackalloc[] { () => { } };
var p6 = stackalloc[] { new {} , new { i = 0 } };
var p7 = stackalloc[] { d };
var p8 = stackalloc[] { _ };
}
public void VoidMethod() {}
}
namespace System {
public struct ValueTuple<T1, T2> {
public ValueTuple(T1 a, T2 b) => throw null;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// void Method(dynamic d, RefStruct r)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28),
// (9,18): error CS0826: No best type found for implicitly-typed array
// var p0 = stackalloc[] { new A(), new B() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18),
// (10,18): error CS0826: No best type found for implicitly-typed array
// var p1 = stackalloc[] { };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18),
// (11,18): error CS0826: No best type found for implicitly-typed array
// var p2 = stackalloc[] { VoidMethod() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18),
// (12,18): error CS0826: No best type found for implicitly-typed array
// var p3 = stackalloc[] { null };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18),
// (13,18): error CS0826: No best type found for implicitly-typed array
// var p4 = stackalloc[] { (1, null) };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18),
// (14,18): error CS0826: No best type found for implicitly-typed array
// var p5 = stackalloc[] { () => { } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18),
// (15,18): error CS0826: No best type found for implicitly-typed array
// var p6 = stackalloc[] { new {} , new { i = 0 } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18),
// (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var p7 = stackalloc[] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18),
// (17,33): error CS0103: The name '_' does not exist in the current context
// var p8 = stackalloc[] { _ };
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33)
);
}
[Fact]
public void NoBestType_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
struct A {}
struct B {}
void Method(dynamic d, bool c)
{
var p0 = c ? default : stackalloc[] { new A(), new B() };
var p1 = c ? default : stackalloc[] { };
var p2 = c ? default : stackalloc[] { VoidMethod() };
var p3 = c ? default : stackalloc[] { null };
var p4 = c ? default : stackalloc[] { (1, null) };
var p5 = c ? default : stackalloc[] { () => { } };
var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } };
var p7 = c ? default : stackalloc[] { d };
var p8 = c ? default : stackalloc[] { _ };
}
public void VoidMethod() {}
}
namespace System {
public struct ValueTuple<T1, T2> {
public ValueTuple(T1 a, T2 b) => throw null;
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (9,32): error CS0826: No best type found for implicitly-typed array
// var p0 = c ? default : stackalloc[] { new A(), new B() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32),
// (10,32): error CS0826: No best type found for implicitly-typed array
// var p1 = c ? default : stackalloc[] { };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32),
// (11,32): error CS0826: No best type found for implicitly-typed array
// var p2 = c ? default : stackalloc[] { VoidMethod() };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32),
// (12,32): error CS0826: No best type found for implicitly-typed array
// var p3 = c ? default : stackalloc[] { null };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32),
// (13,32): error CS0826: No best type found for implicitly-typed array
// var p4 = c ? default : stackalloc[] { (1, null) };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32),
// (14,32): error CS0826: No best type found for implicitly-typed array
// var p5 = c ? default : stackalloc[] { () => { } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32),
// (15,32): error CS0826: No best type found for implicitly-typed array
// var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32),
// (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var p7 = c ? default : stackalloc[] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32),
// (17,47): error CS0103: The name '_' does not exist in the current context
// var p8 = c ? default : stackalloc[] { _ };
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47)
);
}
[Fact]
public void InitializeWithSelf_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void Method1()
{
var obj1 = stackalloc int[1] { obj1 };
var obj2 = stackalloc int[ ] { obj2 };
var obj3 = stackalloc [ ] { obj3 };
}
void Method2()
{
var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[1] { obj1 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40),
// (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40),
// (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40),
// (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40),
// (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50),
// (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40),
// (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50),
// (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40),
// (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50)
);
}
[Fact]
public void InitializeWithSelf_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void Method1(bool c)
{
var obj1 = c ? default : stackalloc int[1] { obj1 };
var obj2 = c ? default : stackalloc int[ ] { obj2 };
var obj3 = c ? default : stackalloc [ ] { obj3 };
}
void Method2(bool c)
{
var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
}
}
", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[1] { obj1 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54),
// (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54),
// (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3 };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54),
// (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54),
// (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared
// var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64),
// (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54),
// (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared
// var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64),
// (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54),
// (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared
// var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64)
);
}
[Fact]
public void BadBestType_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
ref struct S {}
void Method1(S s)
{
var obj1 = stackalloc[] { """" };
var obj2 = stackalloc[] { new {} };
var obj3 = stackalloc[] { s }; // OK
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// var obj1 = stackalloc[] { "" };
Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20),
// (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var obj2 = stackalloc[] { new {} };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.String", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
}
[Fact]
public void BadBestType_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
ref struct S {}
void Method1(S s, bool c)
{
var obj1 = c ? default : stackalloc[] { """" };
var obj2 = c ? default : stackalloc[] { new {} };
var obj3 = c ? default : stackalloc[] { s };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// var obj1 = c ? default : stackalloc[] { "" };
Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34),
// (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var obj2 = c ? default : stackalloc[] { new {} };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34),
// (9,34): error CS0306: The type 'Test.S' may not be used as a type argument
// var obj3 = c ? default : stackalloc[] { s };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.String", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString());
Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString());
Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
}
[Fact]
public void TestFor_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
static void Method1()
{
int i = 0;
for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method2()
{
int i = 0;
for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method3()
{
int i = 0;
for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
public static void Main()
{
Method1();
Method2();
Method3();
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails);
}
[Fact]
public void TestFor_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
static void Method1()
{
int i = 0;
for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method2()
{
int i = 0;
for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
static void Method3()
{
int i = 0;
for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++)
Console.Write(p[i]);
}
public static void Main()
{
Method1();
Method2();
Method3();
}
}", TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
[Fact]
public void TestForTernary()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
class Test
{
static void Method1(bool b)
{
for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {}
for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {}
for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {}
}
}", TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[Fact]
public void TestLock()
{
var source = @"
class Test
{
static void Method1()
{
lock (stackalloc int[3] { 1, 2, 3 }) {}
lock (stackalloc int[ ] { 1, 2, 3 }) {}
lock (stackalloc [ ] { 1, 2, 3 }) {}
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15),
// (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15),
// (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15),
// (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15),
// (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15),
// (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc int[3] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15),
// (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc int[ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15),
// (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement
// lock (stackalloc [ ] { 1, 2, 3 }) {}
Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15)
);
}
[Fact]
public void TestSelect()
{
var source = @"
using System.Linq;
class Test
{
static void Method1(int[] array)
{
var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44),
// (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44),
// (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q1 = from item in array select stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37),
// (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37),
// (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q3 = from item in array select stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37)
);
}
[Fact]
public void TestLet()
{
var source = @"
using System.Linq;
class Test
{
static void Method1(int[] array)
{
var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
}
}";
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3)
.VerifyDiagnostics(
// (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45),
// (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45),
// (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45)
);
CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8)
.VerifyDiagnostics(
// (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75),
// (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75),
// (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument
// var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75)
);
}
[Fact]
public void TestAwait_Pointer()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System.Threading.Tasks;
unsafe class Test
{
async void M()
{
var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,32): error CS4004: Cannot await in an unsafe context
// var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32),
// (7,60): error CS4004: Cannot await in an unsafe context
// var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60)
);
}
[Fact]
public void TestAwait_Span()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
using System.Threading.Tasks;
class Test
{
async void M()
{
Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (8,38): error CS0150: A constant value is expected
// Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38),
// (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions.
// Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9)
);
}
[Fact]
public void TestSelfInSize()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
void M()
{
var x = stackalloc int[x] { };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,32): error CS0841: Cannot use local variable 'x' before it is declared
// var x = stackalloc int[x] { };
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32)
);
}
[Fact]
public void WrongLength()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[10] { };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,20): error CS0847: An array initializer of length '10' is expected
// var obj1 = stackalloc int[10] { };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20)
);
}
[Fact]
public void NoInit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[];
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,34): error CS1586: Array creation must have array size or array initializer
// var obj1 = stackalloc int[];
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34)
);
}
[Fact]
public void NestedInit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[1] { { 42 } };
var obj2 = stackalloc int[ ] { { 42 } };
var obj3 = stackalloc [ ] { { 42 } };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj1 = stackalloc int[1] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40),
// (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj2 = stackalloc int[ ] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40),
// (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
// var obj3 = stackalloc [ ] { { 42 } };
Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40)
);
}
[Fact]
public void AsStatement()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
stackalloc[] {1};
stackalloc int[] {1};
stackalloc int[1] {1};
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc[] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9),
// (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc int[] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9),
// (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// stackalloc int[1] {1};
Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9)
);
}
[Fact]
public void BadRank()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[][] { 1 };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// var obj1 = stackalloc int[][] { 1 };
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31),
// (6,31): error CS1575: A stackalloc expression requires [] after type
// var obj1 = stackalloc int[][] { 1 };
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31)
);
}
[Fact]
public void BadDimension()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc int[,] { 1 };
var obj2 = stackalloc [,] { 1 };
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,35): error CS8381: "Invalid rank specifier: expected ']'
// var obj2 = stackalloc [,] { 1 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35),
// (6,31): error CS1575: A stackalloc expression requires [] after type
// var obj1 = stackalloc int[,] { 1 };
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31)
);
}
[Fact]
public void TestFlowPass1()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
int i, j, k;
var obj1 = stackalloc int [1] { i = 1 };
var obj2 = stackalloc int [ ] { j = 2 };
var obj3 = stackalloc [ ] { k = 3 };
Console.Write(i);
Console.Write(j);
Console.Write(k);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "123");
}
[Fact]
public void TestFlowPass2()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
unsafe class Test
{
public static void Main()
{
int i, j, k;
var obj1 = stackalloc int [1] { i };
var obj2 = stackalloc int [ ] { j };
var obj3 = stackalloc [ ] { k };
}
}", TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (7,41): error CS0165: Use of unassigned local variable 'i'
// var obj1 = stackalloc int [1] { i };
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41),
// (8,41): error CS0165: Use of unassigned local variable 'j'
// var obj2 = stackalloc int [ ] { j };
Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41),
// (9,41): error CS0165: Use of unassigned local variable 'k'
// var obj3 = stackalloc [ ] { k };
Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41)
);
}
[Fact]
public void ConversionFromPointerStackAlloc_UserDefined_Implicit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
Test obj1 = stackalloc int[3] { 1, 2, 3 };
var obj2 = stackalloc int[3] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[3] { 1, 2, 3 };
int* obj4 = stackalloc int[3] { 1, 2, 3 };
double* obj5 = stackalloc int[3] { 1, 2, 3 };
}
public void Method2()
{
Test obj1 = stackalloc int[] { 1, 2, 3 };
var obj2 = stackalloc int[] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[] { 1, 2, 3 };
int* obj4 = stackalloc int[] { 1, 2, 3 };
double* obj5 = stackalloc int[] { 1, 2, 3 };
}
public void Method3()
{
Test obj1 = stackalloc[] { 1, 2, 3 };
var obj2 = stackalloc[] { 1, 2, 3 };
Span<int> obj3 = stackalloc[] { 1, 2, 3 };
int* obj4 = stackalloc[] { 1, 2, 3 };
double* obj5 = stackalloc[] { 1, 2, 3 };
}
public static implicit operator Test(int* value)
{
return default(Test);
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24),
// (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24),
// (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
Assert.Equal(15, variables.Count());
for (int i = 0; i < 15; i += 5)
{
var obj1 = variables.ElementAt(i);
Assert.Equal("obj1", obj1.Identifier.Text);
var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType);
Assert.Equal("Test", obj1Value.ConvertedType.Name);
Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind);
var obj2 = variables.ElementAt(i + 1);
Assert.Equal("obj2", obj2.Identifier.Text);
var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind);
var obj3 = variables.ElementAt(i + 2);
Assert.Equal("obj3", obj3.Identifier.Text);
var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value);
Assert.Equal("Span", obj3Value.Type.Name);
Assert.Equal("Span", obj3Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind);
var obj4 = variables.ElementAt(i + 3);
Assert.Equal("obj4", obj4.Identifier.Text);
var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind);
var obj5 = variables.ElementAt(i + 4);
Assert.Equal("obj5", obj5.Identifier.Text);
var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind);
}
}
[Fact]
public void ConversionFromPointerStackAlloc_UserDefined_Explicit()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 };
var obj2 = stackalloc int[3] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[3] { 1, 2, 3 };
int* obj4 = stackalloc int[3] { 1, 2, 3 };
double* obj5 = stackalloc int[3] { 1, 2, 3 };
}
public void Method2()
{
Test obj1 = (Test)stackalloc int[] { 1, 2, 3 };
var obj2 = stackalloc int[] { 1, 2, 3 };
Span<int> obj3 = stackalloc int[] { 1, 2, 3 };
int* obj4 = stackalloc int[] { 1, 2, 3 };
double* obj5 = stackalloc int[] { 1, 2, 3 };
}
public void Method3()
{
Test obj1 = (Test)stackalloc [] { 1, 2, 3 };
var obj2 = stackalloc[] { 1, 2, 3 };
Span<int> obj3 = stackalloc [] { 1, 2, 3 };
int* obj4 = stackalloc[] { 1, 2, 3 };
double* obj5 = stackalloc[] { 1, 2, 3 };
}
public static explicit operator Test(Span<int> value)
{
return default(Test);
}
}", TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24),
// (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc int[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24),
// (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible.
// double* obj5 = stackalloc[] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
Assert.Equal(15, variables.Count());
for (int i = 0; i < 15; i += 5)
{
var obj1 = variables.ElementAt(i);
Assert.Equal("obj1", obj1.Identifier.Text);
Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind());
var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression);
Assert.Equal("Span", obj1Value.Type.Name);
Assert.Equal("Span", obj1Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind);
var obj2 = variables.ElementAt(i + 1);
Assert.Equal("obj2", obj2.Identifier.Text);
var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind);
var obj3 = variables.ElementAt(i + 2);
Assert.Equal("obj3", obj3.Identifier.Text);
var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value);
Assert.Equal("Span", obj3Value.Type.Name);
Assert.Equal("Span", obj3Value.ConvertedType.Name);
Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind);
var obj4 = variables.ElementAt(i + 3);
Assert.Equal("obj4", obj4.Identifier.Text);
var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind);
var obj5 = variables.ElementAt(i + 4);
Assert.Equal("obj5", obj5.Identifier.Text);
var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind);
}
}
[Fact]
public void ConversionError()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void Method1()
{
double x = stackalloc int[3] { 1, 2, 3 }; // implicit
short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit
}
void Method2()
{
double x = stackalloc int[] { 1, 2, 3 }; // implicit
short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit
}
void Method3()
{
double x = stackalloc[] { 1, 2, 3 }; // implicit
short y = (short)stackalloc[] { 1, 2, 3 }; // explicit
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc int[3] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19),
// (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc int[] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20),
// (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19),
// (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible.
// double x = stackalloc[] { 1, 2, 3 }; // implicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20),
// (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible.
// short y = (short)stackalloc[] { 1, 2, 3 }; // explicit
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19)
);
}
[Fact]
public void MissingSpanType()
{
CreateCompilation(@"
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
}
}").VerifyDiagnostics(
// (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9),
// (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24),
// (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9),
// (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24),
// (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9),
// (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24)
);
}
[Fact]
public void MissingSpanConstructor()
{
CreateCompilation(@"
namespace System
{
ref struct Span<T>
{
}
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
}
}
}").VerifyEmitDiagnostics(
// (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28),
// (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28),
// (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor'
// Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28)
);
}
[Fact]
public void ConditionalExpressionOnSpan_BothStackallocSpans()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_Convertible()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_NoCast()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 };
var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 };
var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59),
// (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59),
// (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible.
// var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 };
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59)
);
}
[Fact]
public void ConditionalExpressionOnSpan_CompatibleTypes()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<int> a1 = stackalloc int [3] { 1, 2, 3 };
Span<int> a2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> a3 = stackalloc [ ] { 1, 2, 3 };
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1;
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2;
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3;
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ConditionalExpressionOnSpan_IncompatibleTypes()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<short> a = stackalloc short [10];
var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a;
var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a;
var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a;
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18),
// (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18),
// (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>'
// var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a;
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18)
);
}
[Fact]
public void ConditionalExpressionOnSpan_Nested()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
bool N() => true;
void M()
{
var x = N()
? N()
? stackalloc int[1] { 42 }
: stackalloc int[ ] { 42 }
: N()
? stackalloc[] { 42 }
: N()
? stackalloc int[2]
: stackalloc int[3];
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void BooleanOperatorOnSpan_NoTargetTyping()
{
CreateCompilationWithMscorlibAndSpan(@"
class Test
{
void M()
{
if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { }
if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { }
if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { }
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13),
// (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13),
// (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { }
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13)
);
}
[Fact]
public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions()
{
var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7);
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
void M()
{
Span<int> x1 = stackalloc int [3] { 1, 2, 3 };
Span<int> x2 = stackalloc int [ ] { 1, 2, 3 };
Span<int> x3 = stackalloc [ ] { 1, 2, 3 };
}
}", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics(
// (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24),
// (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24),
// (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// Span<int> x3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24)
);
}
[Fact]
public void StackAllocSyntaxProducesUnsafeErrorInSafeCode()
{
CreateCompilation(@"
class Test
{
void M()
{
var x1 = stackalloc int [3] { 1, 2, 3 };
var x2 = stackalloc int [ ] { 1, 2, 3 };
var x3 = stackalloc [ ] { 1, 2, 3 };
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18),
// (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18),
// (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18)
);
}
[Fact]
public void StackAllocInUsing1()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
using (var v1 = stackalloc int [3] { 1, 2, 3 })
using (var v2 = stackalloc int [ ] { 1, 2, 3 })
using (var v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16),
// (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16),
// (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16)
);
}
[Fact]
public void StackAllocInUsing2()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 })
using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 })
using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40),
// (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40),
// (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible.
// using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40)
);
}
[Fact]
public void StackAllocInFixed()
{
var test = @"
public class Test
{
unsafe public static void Main()
{
fixed (int* v1 = stackalloc int [3] { 1, 2, 3 })
fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 })
fixed (int* v3 = stackalloc [ ] { 1, 2, 3 })
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v1 = stackalloc int [3] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26),
// (7,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26),
// (8,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* v3 = stackalloc [ ] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26)
);
}
[Fact]
public void ConstStackAllocExpression()
{
var test = @"
unsafe public class Test
{
void M()
{
const int* p1 = stackalloc int [3] { 1, 2, 3 };
const int* p2 = stackalloc int [ ] { 1, 2, 3 };
const int* p3 = stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (6,15): error CS0283: The type 'int*' cannot be declared const
// const int* p1 = stackalloc int[1] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15),
// (7,15): error CS0283: The type 'int*' cannot be declared const
// const int* p2 = stackalloc int[] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15),
// (8,15): error CS0283: The type 'int*' cannot be declared const
// const int* p3 = stackalloc [] { 1 };
Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15)
);
}
[Fact]
public void RefStackAllocAssignment_ValueToRef()
{
var test = @"
using System;
public class Test
{
void M()
{
ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (7,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23),
// (7,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28),
// (8,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23),
// (8,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28),
// (9,23): error CS8172: Cannot initialize a by-reference variable with a value
// ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23),
// (9,28): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28)
);
}
[Fact]
public void RefStackAllocAssignment_RefToRef()
{
var test = @"
using System;
public class Test
{
void M()
{
ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 };
ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 };
ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 };
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (7,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32),
// (8,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32),
// (9,32): error CS1510: A ref or out value must be an assignable variable
// ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32)
);
}
[Fact]
public void InvalidPositionForStackAllocSpan()
{
var test = @"
using System;
public class Test
{
void M()
{
N(stackalloc int [3] { 1, 2, 3 });
N(stackalloc int [ ] { 1, 2, 3 });
N(stackalloc [ ] { 1, 2, 3 });
}
void N(Span<int> span)
{
}
}
";
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11),
// (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11),
// (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11)
);
CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics(
);
}
[Fact]
public void CannotDotIntoStackAllocExpression()
{
var test = @"
public class Test
{
void M()
{
int length1 = (stackalloc int [3] { 1, 2, 3 }).Length;
int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length;
int length3 = (stackalloc [ ] { 1, 2, 3 }).Length;
int length4 = stackalloc int [3] { 1, 2, 3 }.Length;
int length5 = stackalloc int [ ] { 1, 2, 3 }.Length;
int length6 = stackalloc [ ] { 1, 2, 3 }.Length;
}
}
";
CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length1 = (stackalloc int [3] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24),
// (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24),
// (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length3 = (stackalloc [ ] { 1, 2, 3 }).Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24),
// (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length4 = stackalloc int [3] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23),
// (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length5 = stackalloc int [ ] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23),
// (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int length6 = stackalloc [ ] { 1, 2, 3 }.Length;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23)
);
CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact]
public void OverloadResolution_Fail()
{
var test = @"
using System;
unsafe public class Test
{
static void Main()
{
Invoke(stackalloc int [3] { 1, 2, 3 });
Invoke(stackalloc int [ ] { 1, 2, 3 });
Invoke(stackalloc [ ] { 1, 2, 3 });
}
static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan"");
static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan"");
static void Invoke(int* intPointer) => Console.WriteLine(""intPointer"");
static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer"");
}
";
CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16),
// (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16),
// (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// Invoke(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16)
);
CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics(
// (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16),
// (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16),
// (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>'
// Invoke(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16)
);
}
[Fact]
public void StackAllocWithDynamic()
{
CreateCompilation(@"
class Program
{
static void Main()
{
dynamic d = 1;
var d1 = stackalloc dynamic [3] { d };
var d2 = stackalloc dynamic [ ] { d };
var d3 = stackalloc [ ] { d };
}
}").VerifyDiagnostics(
// (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29),
// (7,18): error CS0847: An array initializer of length '3' is expected
// var d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18),
// (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d2 = stackalloc dynamic [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29),
// (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// var d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18),
// (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18)
);
}
[Fact]
public void StackAllocWithDynamicSpan()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Program
{
static void Main()
{
dynamic d = 1;
Span<dynamic> d1 = stackalloc dynamic [3] { d };
Span<dynamic> d2 = stackalloc dynamic [ ] { d };
Span<dynamic> d3 = stackalloc [ ] { d };
}
}").VerifyDiagnostics(
// (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39),
// (8,28): error CS0847: An array initializer of length '3' is expected
// Span<dynamic> d1 = stackalloc dynamic [3] { d };
Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28),
// (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d2 = stackalloc dynamic [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39),
// (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')
// Span<dynamic> d3 = stackalloc [ ] { d };
Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28)
);
}
[Fact]
public void StackAllocAsArgument()
{
var source = @"
class Program
{
static void N(object p) { }
static void Main()
{
N(stackalloc int [3] { 1, 2, 3 });
N(stackalloc int [ ] { 1, 2, 3 });
N(stackalloc [ ] { 1, 2, 3 });
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11),
// (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11),
// (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11)
);
CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics(
// (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11),
// (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11),
// (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object'
// N(stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11)
);
}
[Fact]
public void StackAllocInParenthesis()
{
var source = @"
class Program
{
static void Main()
{
var x1 = (stackalloc int [3] { 1, 2, 3 });
var x2 = (stackalloc int [ ] { 1, 2, 3 });
var x3 = (stackalloc [ ] { 1, 2, 3 });
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = (stackalloc int [3] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19),
// (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = (stackalloc int [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19),
// (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = (stackalloc [ ] { 1, 2, 3 });
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19)
);
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
);
}
[Fact]
public void StackAllocInNullConditionalOperator()
{
var source = @"
class Program
{
static void Main()
{
var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
}
}";
CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18),
// (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52),
// (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18),
// (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52),
// (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18),
// (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52)
);
CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18),
// (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18),
// (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>'
// var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18)
);
}
[Fact]
public void StackAllocInCastAndConditionalOperator()
{
CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public void Method()
{
Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 };
Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 };
Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 };
}
public static explicit operator Test(Span<int> value)
{
return new Test();
}
}", TestOptions.ReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ERR_StackallocInCatchFinally_Catch()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err11 = stackalloc int [3] { 1, 2, 3 };
int* err12 = stackalloc int [ ] { 1, 2, 3 };
int* err13 = stackalloc [ ] { 1, 2, 3 };
}
};
}
catch
{
int* err21 = stackalloc int [3] { 1, 2, 3 };
int* err22 = stackalloc int [ ] { 1, 2, 3 };
int* err23 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err31 = stackalloc int [3] { 1, 2, 3 };
int* err32 = stackalloc int [ ] { 1, 2, 3 };
int* err33 = stackalloc [ ] { 1, 2, 3 };
}
};
}
});
static int M(System.Action action)
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err41 = stackalloc int [3] { 1, 2, 3 };
int* err42 = stackalloc int [ ] { 1, 2, 3 };
int* err43 = stackalloc [ ] { 1, 2, 3 };
}
};
}
catch
{
int* err51 = stackalloc int [3] { 1, 2, 3 };
int* err52 = stackalloc int [ ] { 1, 2, 3 };
int* err53 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
catch
{
int* err61 = stackalloc int [3] { 1, 2, 3 };
int* err62 = stackalloc int [ ] { 1, 2, 3 };
int* err63 = stackalloc [ ] { 1, 2, 3 };
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (23,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err11 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34),
// (24,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err12 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34),
// (25,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err13 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34),
// (31,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err21 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26),
// (32,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err22 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26),
// (33,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err23 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26),
// (45,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err31 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34),
// (46,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err32 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34),
// (47,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err33 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34),
// (72,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err41 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34),
// (73,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err42 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34),
// (74,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err43 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34),
// (80,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err51 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26),
// (81,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err52 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26),
// (82,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err53 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26),
// (94,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err61 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34),
// (95,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err62 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34),
// (96,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err63 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34)
);
}
[Fact]
public void ERR_StackallocInCatchFinally_Finally()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err11 = stackalloc int [3] { 1, 2, 3 };
int* err12 = stackalloc int [ ] { 1, 2, 3 };
int* err13 = stackalloc [ ] { 1, 2, 3 };
}
};
}
finally
{
int* err21 = stackalloc int [3] { 1, 2, 3 };
int* err22 = stackalloc int [ ] { 1, 2, 3 };
int* err23 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err31 = stackalloc int [3] { 1, 2, 3 };
int* err32 = stackalloc int [ ] { 1, 2, 3 };
int* err33 = stackalloc [ ] { 1, 2, 3 };
}
};
}
});
static int M(System.Action action)
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* q1 = stackalloc int [3] { 1, 2, 3 };
int* q2 = stackalloc int [ ] { 1, 2, 3 };
int* q3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err41 = stackalloc int [3] { 1, 2, 3 };
int* err42 = stackalloc int [ ] { 1, 2, 3 };
int* err43 = stackalloc [ ] { 1, 2, 3 };
}
};
}
finally
{
int* err51 = stackalloc int [3] { 1, 2, 3 };
int* err52 = stackalloc int [ ] { 1, 2, 3 };
int* err53 = stackalloc [ ] { 1, 2, 3 };
System.Action a = () =>
{
try
{
// fine
int* p1 = stackalloc int [3] { 1, 2, 3 };
int* p2 = stackalloc int [ ] { 1, 2, 3 };
int* p3 = stackalloc [ ] { 1, 2, 3 };
}
finally
{
int* err61 = stackalloc int [3] { 1, 2, 3 };
int* err62 = stackalloc int [ ] { 1, 2, 3 };
int* err63 = stackalloc [ ] { 1, 2, 3 };
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (23,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err11 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34),
// (24,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err12 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34),
// (25,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err13 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34),
// (31,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err21 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26),
// (32,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err22 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26),
// (33,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err23 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26),
// (45,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err31 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34),
// (46,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err32 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34),
// (47,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err33 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34),
// (72,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err41 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34),
// (73,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err42 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34),
// (74,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err43 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34),
// (80,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err51 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26),
// (81,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err52 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26),
// (82,26): error CS0255: stackalloc may not be used in a catch or finally block
// int* err53 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26),
// (94,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err61 = stackalloc int [3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34),
// (95,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err62 = stackalloc int [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34),
// (96,34): error CS0255: stackalloc may not be used in a catch or finally block
// int* err63 = stackalloc [ ] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34)
);
}
[Fact]
public void StackAllocArrayCreationExpression_Symbols()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc double[2] { 1, 1.2 };
Span<double> obj2 = stackalloc double[2] { 1, 1.2 };
_ = stackalloc double[2] { 1, 1.2 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method
// _ = stackalloc double[2] { 1, 1.2 };
Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void ImplicitStackAllocArrayCreationExpression_Symbols()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
var obj1 = stackalloc[] { 1, 1.2 };
Span<double> obj2 = stackalloc[] { 1, 1.2 };
_ = stackalloc[] { 1, 1.2 };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method
// _ = stackalloc[] { 1, 1.2 };
Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(3, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[2];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void StackAllocArrayCreationExpression_Symbols_ErrorCase()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,41): error CS0150: A constant value is expected
// short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41),
// (8,46): error CS0150: A constant value is expected
// Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46),
// (7,42): error CS0165: Use of unassigned local variable 'obj1'
// short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42),
// (8,46): error CS0165: Use of unassigned local variable 'obj2'
// Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(2, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Null(sizeInfo.Symbol);
Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]);
Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
[Fact]
public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public void Method1()
{
double* obj1 = stackalloc[] { obj1[0], *obj1 };
Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length };
}
}", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,39): error CS0165: Use of unassigned local variable 'obj1'
// double* obj1 = stackalloc[] { obj1[0], *obj1 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39),
// (8,44): error CS0165: Use of unassigned local variable 'obj2'
// Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length };
Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray();
Assert.Equal(2, expressions.Length);
var @stackalloc = expressions[0];
var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Null(element0Info.Symbol);
Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Null(element1Info.Symbol);
Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
@stackalloc = expressions[1];
stackallocInfo = model.GetSemanticInfoSummary(@stackalloc);
Assert.Null(stackallocInfo.Symbol);
Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString());
Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion);
element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]);
Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion);
element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]);
Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString());
Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString());
Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion);
Assert.Null(model.GetDeclaredSymbol(@stackalloc));
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
/// <summary>
/// Service that can be used to generate <see cref="object.Equals(object)"/> and
/// <see cref="object.GetHashCode"/> overloads for use from other IDE features.
/// </summary>
internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService
{
/// <summary>
/// Formats only the members in the provided document that were generated by this interface.
/// </summary>
Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.Equals(object)"/> that works by comparing the
/// provided <paramref name="members"/>.
/// </summary>
Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string? localNameOpt, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.Equals(object)"/> that works by delegating to
/// <see cref="IEquatable{T}.Equals(T)"/>.
/// </summary>
Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken);
/// <summary>
/// Generates an implementation of <see cref="IEquatable{T}.Equals"/> that works by
/// comparing the provided <paramref name="members"/>.
/// </summary>
Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, INamedTypeSymbol constructedEquatableType, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.GetHashCode"/> that computes a reasonable
/// hash based on the provided <paramref name="members"/>. The generated function will
/// defer to HashCode.Combine if it exists. Otherwise, it will determine if it should
/// generate code directly in-line to compute the hash, or defer to something like
/// <see cref="ValueTuple.GetHashCode"/> to provide a reasonable alternative.
/// </summary>
Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, 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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
/// <summary>
/// Service that can be used to generate <see cref="object.Equals(object)"/> and
/// <see cref="object.GetHashCode"/> overloads for use from other IDE features.
/// </summary>
internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService
{
/// <summary>
/// Formats only the members in the provided document that were generated by this interface.
/// </summary>
Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.Equals(object)"/> that works by comparing the
/// provided <paramref name="members"/>.
/// </summary>
Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string? localNameOpt, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.Equals(object)"/> that works by delegating to
/// <see cref="IEquatable{T}.Equals(T)"/>.
/// </summary>
Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken);
/// <summary>
/// Generates an implementation of <see cref="IEquatable{T}.Equals"/> that works by
/// comparing the provided <paramref name="members"/>.
/// </summary>
Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, INamedTypeSymbol constructedEquatableType, CancellationToken cancellationToken);
/// <summary>
/// Generates an override of <see cref="object.GetHashCode"/> that computes a reasonable
/// hash based on the provided <paramref name="members"/>. The generated function will
/// defer to HashCode.Combine if it exists. Otherwise, it will determine if it should
/// generate code directly in-line to compute the hash, or defer to something like
/// <see cref="ValueTuple.GetHashCode"/> to provide a reasonable alternative.
/// </summary>
Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/FSharp/SignatureHelp/IFSharpSignatureHelpProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp
{
internal interface IFSharpSignatureHelpProvider
{
/// <summary>
/// Returns true if the character might trigger completion,
/// e.g. '(' and ',' for method invocations
/// </summary>
bool IsTriggerCharacter(char ch);
/// <summary>
/// Returns true if the character might end a Signature Help session,
/// e.g. ')' for method invocations.
/// </summary>
bool IsRetriggerCharacter(char ch);
/// <summary>
/// Returns valid signature help items at the specified position in the document.
/// </summary>
Task<FSharpSignatureHelpItems> GetItemsAsync(Document document, int position, FSharpSignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp
{
internal interface IFSharpSignatureHelpProvider
{
/// <summary>
/// Returns true if the character might trigger completion,
/// e.g. '(' and ',' for method invocations
/// </summary>
bool IsTriggerCharacter(char ch);
/// <summary>
/// Returns true if the character might end a Signature Help session,
/// e.g. ')' for method invocations.
/// </summary>
bool IsRetriggerCharacter(char ch);
/// <summary>
/// Returns valid signature help items at the specified position in the document.
/// </summary>
Task<FSharpSignatureHelpItems> GetItemsAsync(Document document, int position, FSharpSignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.TestState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.MoveToNamespace;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.Test.Utilities.MoveToNamespace
{
public abstract partial class AbstractMoveToNamespaceTests
{
internal class TestState : IDisposable
{
public TestState(TestWorkspace workspace)
=> Workspace = workspace;
public void Dispose()
=> Workspace?.Dispose();
public TestWorkspace Workspace { get; }
public TestHostDocument TestInvocationDocument => Workspace.Documents.Single();
public Document InvocationDocument => Workspace.CurrentSolution.GetDocument(TestInvocationDocument.Id);
public TestMoveToNamespaceOptionsService TestMoveToNamespaceOptionsService
=> (TestMoveToNamespaceOptionsService)MoveToNamespaceService.OptionsService;
public IMoveToNamespaceService MoveToNamespaceService
=> InvocationDocument.GetRequiredLanguageService<IMoveToNamespaceService>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.MoveToNamespace;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.Test.Utilities.MoveToNamespace
{
public abstract partial class AbstractMoveToNamespaceTests
{
internal class TestState : IDisposable
{
public TestState(TestWorkspace workspace)
=> Workspace = workspace;
public void Dispose()
=> Workspace?.Dispose();
public TestWorkspace Workspace { get; }
public TestHostDocument TestInvocationDocument => Workspace.Documents.Single();
public Document InvocationDocument => Workspace.CurrentSolution.GetDocument(TestInvocationDocument.Id);
public TestMoveToNamespaceOptionsService TestMoveToNamespaceOptionsService
=> (TestMoveToNamespaceOptionsService)MoveToNamespaceService.OptionsService;
public IMoveToNamespaceService MoveToNamespaceService
=> InvocationDocument.GetRequiredLanguageService<IMoveToNamespaceService>();
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/ExtractMethod/MethodExtractor.VariableSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class MethodExtractor
{
/// <summary>
/// temporary symbol until we have a symbol that can hold onto both local and parameter symbol
/// </summary>
protected abstract class VariableSymbol
{
protected VariableSymbol(Compilation compilation, ITypeSymbol type)
{
OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType();
OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type;
}
public abstract int DisplayOrder { get; }
public abstract string Name { get; }
public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken);
public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; }
public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken);
public abstract void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken);
protected abstract int CompareTo(VariableSymbol right);
/// <summary>
/// return true if original type had anonymous type or delegate somewhere in the type
/// </summary>
public bool OriginalTypeHadAnonymousTypeOrDelegate { get; }
/// <summary>
/// get the original type with anonymous type removed
/// </summary>
public ITypeSymbol OriginalType { get; }
public static int Compare(
VariableSymbol left,
VariableSymbol right,
INamedTypeSymbol cancellationTokenType)
{
// CancellationTokens always go at the end of method signature.
var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType);
var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType);
if (leftIsCancellationToken && !rightIsCancellationToken)
{
return 1;
}
else if (!leftIsCancellationToken && rightIsCancellationToken)
{
return -1;
}
if (left.DisplayOrder == right.DisplayOrder)
{
return left.CompareTo(right);
}
return left.DisplayOrder - right.DisplayOrder;
}
}
protected abstract class NotMovableVariableSymbol : VariableSymbol
{
public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type)
: base(compilation, type)
{
}
public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
{
// decl never get moved
return false;
}
public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
=> throw ExceptionUtilities.Unreachable;
public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable;
public override void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
{
// do nothing for parameter
}
}
protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol>
{
private readonly IParameterSymbol _parameterSymbol;
public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type)
: base(compilation, type)
{
Contract.ThrowIfNull(parameterSymbol);
_parameterSymbol = parameterSymbol;
}
public override int DisplayOrder => 0;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((ParameterVariableSymbol)right);
public int CompareTo(ParameterVariableSymbol other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol);
if (compare != 0)
{
return compare;
}
Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal);
return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1;
}
private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right)
{
if (left == null && right == null)
{
// not method parameters
return 0;
}
if (left.Equals(right))
{
// parameter of same method
return 0;
}
// these methods can be either regular one, anonymous function, local function and etc
// but all must belong to same outer regular method.
// so, it should have location pointing to same tree
var leftLocations = left.Locations;
var rightLocations = right.Locations;
var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First();
var leftLocation = leftLocations.First(l => l.SourceTree == commonTree);
var rightLocation = rightLocations.First(l => l.SourceTree == commonTree);
return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start;
}
public override string Name
{
get
{
return _parameterSymbol.ToDisplayString(
new SymbolDisplayFormat(
parameterOptions: SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
}
protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode
{
private readonly SyntaxAnnotation _annotation;
private readonly ILocalSymbol _localSymbol;
private readonly HashSet<int> _nonNoisySet;
public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet)
: base(compilation, type)
{
Contract.ThrowIfNull(localSymbol);
Contract.ThrowIfNull(nonNoisySet);
_annotation = new SyntaxAnnotation();
_localSymbol = localSymbol;
_nonNoisySet = nonNoisySet;
}
public override int DisplayOrder => 1;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((LocalVariableSymbol<T>)right);
public int CompareTo(LocalVariableSymbol<T> other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource);
Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree);
Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start);
return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start;
}
public override string Name
{
get
{
return _localSymbol.ToDisplayString(
new SymbolDisplayFormat(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree);
var tree = _localSymbol.Locations[0].SourceTree;
var span = _localSymbol.Locations[0].SourceSpan;
var token = tree.GetRoot(cancellationToken).FindToken(span.Start);
Contract.ThrowIfFalse(token.Span.Equals(span));
return token;
}
public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation;
public override void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
{
annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation));
}
public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
{
var identifier = GetOriginalIdentifierToken(cancellationToken);
// check whether there is a noisy trivia around the token.
if (ContainsNoisyTrivia(identifier.LeadingTrivia))
{
return true;
}
if (ContainsNoisyTrivia(identifier.TrailingTrivia))
{
return true;
}
var declStatement = identifier.Parent.FirstAncestorOrSelf<T>();
if (declStatement == null)
{
return true;
}
foreach (var token in declStatement.DescendantTokens())
{
if (ContainsNoisyTrivia(token.LeadingTrivia))
{
return true;
}
if (ContainsNoisyTrivia(token.TrailingTrivia))
{
return true;
}
}
return false;
}
private bool ContainsNoisyTrivia(SyntaxTriviaList list)
=> list.Any(t => !_nonNoisySet.Contains(t.RawKind));
}
protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol>
{
private readonly IRangeVariableSymbol _symbol;
public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type)
: base(compilation, type)
{
Contract.ThrowIfNull(symbol);
_symbol = symbol;
}
public override int DisplayOrder => 2;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((QueryVariableSymbol)right);
public int CompareTo(QueryVariableSymbol other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
var locationLeft = _symbol.Locations.First();
var locationRight = other._symbol.Locations.First();
Contract.ThrowIfFalse(locationLeft.IsInSource);
Contract.ThrowIfFalse(locationRight.IsInSource);
Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree);
Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start);
return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start;
}
public override string Name
{
get
{
return _symbol.ToDisplayString(
new SymbolDisplayFormat(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class MethodExtractor
{
/// <summary>
/// temporary symbol until we have a symbol that can hold onto both local and parameter symbol
/// </summary>
protected abstract class VariableSymbol
{
protected VariableSymbol(Compilation compilation, ITypeSymbol type)
{
OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType();
OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type;
}
public abstract int DisplayOrder { get; }
public abstract string Name { get; }
public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken);
public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; }
public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken);
public abstract void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken);
protected abstract int CompareTo(VariableSymbol right);
/// <summary>
/// return true if original type had anonymous type or delegate somewhere in the type
/// </summary>
public bool OriginalTypeHadAnonymousTypeOrDelegate { get; }
/// <summary>
/// get the original type with anonymous type removed
/// </summary>
public ITypeSymbol OriginalType { get; }
public static int Compare(
VariableSymbol left,
VariableSymbol right,
INamedTypeSymbol cancellationTokenType)
{
// CancellationTokens always go at the end of method signature.
var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType);
var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType);
if (leftIsCancellationToken && !rightIsCancellationToken)
{
return 1;
}
else if (!leftIsCancellationToken && rightIsCancellationToken)
{
return -1;
}
if (left.DisplayOrder == right.DisplayOrder)
{
return left.CompareTo(right);
}
return left.DisplayOrder - right.DisplayOrder;
}
}
protected abstract class NotMovableVariableSymbol : VariableSymbol
{
public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type)
: base(compilation, type)
{
}
public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
{
// decl never get moved
return false;
}
public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
=> throw ExceptionUtilities.Unreachable;
public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable;
public override void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
{
// do nothing for parameter
}
}
protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol>
{
private readonly IParameterSymbol _parameterSymbol;
public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type)
: base(compilation, type)
{
Contract.ThrowIfNull(parameterSymbol);
_parameterSymbol = parameterSymbol;
}
public override int DisplayOrder => 0;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((ParameterVariableSymbol)right);
public int CompareTo(ParameterVariableSymbol other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol);
if (compare != 0)
{
return compare;
}
Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal);
return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1;
}
private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right)
{
if (left == null && right == null)
{
// not method parameters
return 0;
}
if (left.Equals(right))
{
// parameter of same method
return 0;
}
// these methods can be either regular one, anonymous function, local function and etc
// but all must belong to same outer regular method.
// so, it should have location pointing to same tree
var leftLocations = left.Locations;
var rightLocations = right.Locations;
var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First();
var leftLocation = leftLocations.First(l => l.SourceTree == commonTree);
var rightLocation = rightLocations.First(l => l.SourceTree == commonTree);
return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start;
}
public override string Name
{
get
{
return _parameterSymbol.ToDisplayString(
new SymbolDisplayFormat(
parameterOptions: SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
}
protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode
{
private readonly SyntaxAnnotation _annotation;
private readonly ILocalSymbol _localSymbol;
private readonly HashSet<int> _nonNoisySet;
public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet)
: base(compilation, type)
{
Contract.ThrowIfNull(localSymbol);
Contract.ThrowIfNull(nonNoisySet);
_annotation = new SyntaxAnnotation();
_localSymbol = localSymbol;
_nonNoisySet = nonNoisySet;
}
public override int DisplayOrder => 1;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((LocalVariableSymbol<T>)right);
public int CompareTo(LocalVariableSymbol<T> other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource);
Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree);
Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start);
return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start;
}
public override string Name
{
get
{
return _localSymbol.ToDisplayString(
new SymbolDisplayFormat(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree);
var tree = _localSymbol.Locations[0].SourceTree;
var span = _localSymbol.Locations[0].SourceSpan;
var token = tree.GetRoot(cancellationToken).FindToken(span.Start);
Contract.ThrowIfFalse(token.Span.Equals(span));
return token;
}
public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation;
public override void AddIdentifierTokenAnnotationPair(
List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
{
annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation));
}
public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
{
var identifier = GetOriginalIdentifierToken(cancellationToken);
// check whether there is a noisy trivia around the token.
if (ContainsNoisyTrivia(identifier.LeadingTrivia))
{
return true;
}
if (ContainsNoisyTrivia(identifier.TrailingTrivia))
{
return true;
}
var declStatement = identifier.Parent.FirstAncestorOrSelf<T>();
if (declStatement == null)
{
return true;
}
foreach (var token in declStatement.DescendantTokens())
{
if (ContainsNoisyTrivia(token.LeadingTrivia))
{
return true;
}
if (ContainsNoisyTrivia(token.TrailingTrivia))
{
return true;
}
}
return false;
}
private bool ContainsNoisyTrivia(SyntaxTriviaList list)
=> list.Any(t => !_nonNoisySet.Contains(t.RawKind));
}
protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol>
{
private readonly IRangeVariableSymbol _symbol;
public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type)
: base(compilation, type)
{
Contract.ThrowIfNull(symbol);
_symbol = symbol;
}
public override int DisplayOrder => 2;
protected override int CompareTo(VariableSymbol right)
=> CompareTo((QueryVariableSymbol)right);
public int CompareTo(QueryVariableSymbol other)
{
Contract.ThrowIfNull(other);
if (this == other)
{
return 0;
}
var locationLeft = _symbol.Locations.First();
var locationRight = other._symbol.Locations.First();
Contract.ThrowIfFalse(locationLeft.IsInSource);
Contract.ThrowIfFalse(locationRight.IsInSource);
Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree);
Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start);
return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start;
}
public override string Name
{
get
{
return _symbol.ToDisplayString(
new SymbolDisplayFormat(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/GroupKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public GroupKeywordRecommender()
: base(SyntaxKind.GroupKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var token = context.TargetToken;
// var q = from x in y
// |
if (!token.IntersectsWith(position) &&
token.IsLastTokenOfQueryClause())
{
return true;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public GroupKeywordRecommender()
: base(SyntaxKind.GroupKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var token = context.TargetToken;
// var q = from x in y
// |
if (!token.IntersectsWith(position) &&
token.IsLastTokenOfQueryClause())
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset);
internal sealed class MetadataResolver<TProcess, TModule, TRequest>
where TProcess : class
where TModule : class
where TRequest : class
{
private readonly TProcess _process;
private readonly TModule _module;
private readonly MetadataReader _reader;
private readonly StringComparer _stringComparer; // for comparing strings
private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles
private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved;
internal MetadataResolver(
TProcess process,
TModule module,
MetadataReader reader,
bool ignoreCase,
OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved)
{
_process = process;
_module = module;
_reader = reader;
_stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
_ignoreCase = ignoreCase;
_onFunctionResolved = onFunctionResolved;
}
internal void Resolve(TRequest request, RequestSignature signature)
{
QualifiedName qualifiedTypeName;
ImmutableArray<string> memberTypeParameters;
GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters);
var typeName = qualifiedTypeName.Qualifier;
var memberName = qualifiedTypeName.Name;
var memberParameters = signature.Parameters;
var allTypeParameters = GetAllGenericTypeParameters(typeName);
foreach (var typeHandle in _reader.TypeDefinitions)
{
var typeDef = _reader.GetTypeDefinition(typeHandle);
int containingArity = CompareToTypeDefinition(typeDef, typeName);
if (containingArity < 0)
{
continue;
}
// Visit methods.
foreach (var methodHandle in typeDef.GetMethods())
{
var methodDef = _reader.GetMethodDefinition(methodHandle);
if (!IsResolvableMethod(methodDef))
{
continue;
}
if (MatchesMethod(typeDef, methodDef, typeName, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters))
{
OnFunctionResolved(request, methodHandle);
}
}
if (memberTypeParameters.IsEmpty)
{
// Visit properties.
foreach (var propertyHandle in typeDef.GetProperties())
{
var propertyDef = _reader.GetPropertyDefinition(propertyHandle);
if (MatchesProperty(typeDef, propertyDef, typeName, memberName, allTypeParameters, containingArity, memberParameters))
{
var accessors = propertyDef.GetAccessors();
OnAccessorResolved(request, accessors.Getter);
OnAccessorResolved(request, accessors.Setter);
}
}
}
}
}
// If the signature matches the TypeDefinition, including some or all containing
// types and namespaces, returns a non-negative value indicating the arity of the
// containing types that were not specified in the signature; otherwise returns -1.
// For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D,
// where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1
// is the arity of the containing types A<T>.B that were missing from the signature.
// "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire
// signature, from nested TypeDefinition, out.
private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature)
{
if (signature == null)
{
return typeDef.GetGenericParameters().Count;
}
QualifiedName qualifiedName;
ImmutableArray<string> typeParameters;
GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters);
if (!MatchesTypeName(typeDef, qualifiedName.Name))
{
return -1;
}
var declaringTypeHandle = typeDef.GetDeclaringType();
var declaringType = declaringTypeHandle.IsNil ? default(TypeDefinition) : _reader.GetTypeDefinition(declaringTypeHandle);
int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count;
if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount))
{
return -1;
}
var qualifier = qualifiedName.Qualifier;
if (declaringTypeHandle.IsNil)
{
// Compare namespace.
return MatchesNamespace(typeDef, qualifier) ? 0 : -1;
}
else
{
// Compare declaring type.
return CompareToTypeDefinition(declaringType, qualifier);
}
}
private bool MatchesNamespace(TypeDefinition typeDef, Name signature)
{
if (signature == null)
{
return true;
}
var namespaceName = _reader.GetString(typeDef.Namespace);
if (string.IsNullOrEmpty(namespaceName))
{
return false;
}
var parts = namespaceName.Split('.');
for (int index = parts.Length - 1; index >= 0; index--)
{
if (signature == null)
{
return true;
}
var qualifiedName = signature as QualifiedName;
if (qualifiedName == null)
{
return false;
}
var part = parts[index];
if (!_stringComparer.Equals(qualifiedName.Name, part))
{
return false;
}
signature = qualifiedName.Qualifier;
}
return signature == null;
}
private bool MatchesTypeName(TypeDefinition typeDef, string name)
{
var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name));
return _stringComparer.Equals(typeName, name);
}
private bool MatchesMethod(
TypeDefinition typeDef,
MethodDefinition methodDef,
Name typeName,
string methodName,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<string> methodTypeParameters,
ImmutableArray<ParameterSignature> methodParameters)
{
if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0)
{
if (!_reader.StringComparer.Equals(methodDef.Name, ".ctor", ignoreCase: false))
{
// Unhandled special name.
return false;
}
if (!MatchesTypeName(typeDef, methodName))
{
return false;
}
}
else if (!_reader.StringComparer.Equals(methodDef.Name, methodName, _ignoreCase))
{
return false;
}
if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0))
{
return false;
}
if (methodParameters.IsDefault)
{
return true;
}
return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters);
}
private bool MatchesProperty(
TypeDefinition typeDef,
PropertyDefinition propertyDef,
Name typeName,
string propertyName,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<ParameterSignature> propertyParameters)
{
if (!_reader.StringComparer.Equals(propertyDef.Name, propertyName, _ignoreCase))
{
return false;
}
if (propertyParameters.IsDefault)
{
return true;
}
if (propertyParameters.Length == 0)
{
// Parameter-less properties should be specified
// with no parameter list.
return false;
}
// Match parameters against getter. Not supporting
// matching against setter for write-only properties.
var methodHandle = propertyDef.GetAccessors().Getter;
if (methodHandle.IsNil)
{
return false;
}
var methodDef = _reader.GetMethodDefinition(methodHandle);
return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters);
}
private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName)
{
var builder = ImmutableArray.CreateBuilder<string>();
GetAllGenericTypeParameters(typeName, builder);
return builder.ToImmutable();
}
private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder)
{
if (typeName == null)
{
return;
}
QualifiedName qualifiedName;
ImmutableArray<string> typeParameters;
GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters);
GetAllGenericTypeParameters(qualifiedName.Qualifier, builder);
builder.AddRange(typeParameters);
}
private bool MatchesParameters(
MethodDefinition methodDef,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<string> methodTypeParameters,
ImmutableArray<ParameterSignature> methodParameters)
{
ImmutableArray<ParameterSignature> parameters;
try
{
var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters);
parameters = decoder.DecodeParameters(methodDef);
}
catch (NotSupportedException)
{
return false;
}
catch (BadImageFormatException)
{
return false;
}
return methodParameters.SequenceEqual(parameters, MatchesParameter);
}
private void OnFunctionResolved(
TRequest request,
MethodDefinitionHandle handle)
{
Debug.Assert(!handle.IsNil);
_onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0);
}
private void OnAccessorResolved(
TRequest request,
MethodDefinitionHandle handle)
{
if (handle.IsNil)
{
return;
}
var methodDef = _reader.GetMethodDefinition(handle);
if (IsResolvableMethod(methodDef))
{
OnFunctionResolved(request, handle);
}
}
private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset)
{
return typeArguments.Length == typeParameters.Count - offset;
}
// parameterA from string signature, parameterB from metadata.
private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB)
{
return MatchesType(parameterA.Type, parameterB.Type) &&
parameterA.IsByRef == parameterB.IsByRef;
}
// typeA from string signature, typeB from metadata.
private bool MatchesType(TypeSignature typeA, TypeSignature typeB)
{
if (typeA.Kind != typeB.Kind)
{
return false;
}
switch (typeA.Kind)
{
case TypeSignatureKind.GenericType:
{
var genericA = (GenericTypeSignature)typeA;
var genericB = (GenericTypeSignature)typeB;
return MatchesType(genericA.QualifiedName, genericB.QualifiedName) &&
genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType);
}
case TypeSignatureKind.QualifiedType:
{
var qualifiedA = (QualifiedTypeSignature)typeA;
var qualifiedB = (QualifiedTypeSignature)typeB;
// Metadata signature may be more qualified than the
// string signature but still considered a match
// (e.g.: "B<U>.C" should match N.A<T>.B<U>.C).
return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) &&
_stringComparer.Equals(qualifiedA.Name, qualifiedB.Name);
}
case TypeSignatureKind.ArrayType:
{
var arrayA = (ArrayTypeSignature)typeA;
var arrayB = (ArrayTypeSignature)typeB;
return MatchesType(arrayA.ElementType, arrayB.ElementType) &&
arrayA.Rank == arrayB.Rank;
}
case TypeSignatureKind.PointerType:
{
var pointerA = (PointerTypeSignature)typeA;
var pointerB = (PointerTypeSignature)typeB;
return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType);
}
default:
throw ExceptionUtilities.UnexpectedValue(typeA.Kind);
}
}
private static void GetNameAndTypeParameters(
Name name,
out QualifiedName qualifiedName,
out ImmutableArray<string> typeParameters)
{
switch (name.Kind)
{
case NameKind.GenericName:
{
var genericName = (GenericName)name;
qualifiedName = genericName.QualifiedName;
typeParameters = genericName.TypeParameters;
}
break;
case NameKind.QualifiedName:
{
qualifiedName = (QualifiedName)name;
typeParameters = ImmutableArray<string>.Empty;
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(name.Kind);
}
}
private static bool IsResolvableMethod(MethodDefinition methodDef)
{
return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0;
}
private static string RemoveAritySeparatorIfAny(string typeName)
{
int index = typeName.LastIndexOf('`');
return (index < 0) ? typeName : typeName.Substring(0, index);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset);
internal sealed class MetadataResolver<TProcess, TModule, TRequest>
where TProcess : class
where TModule : class
where TRequest : class
{
private readonly TProcess _process;
private readonly TModule _module;
private readonly MetadataReader _reader;
private readonly StringComparer _stringComparer; // for comparing strings
private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles
private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved;
internal MetadataResolver(
TProcess process,
TModule module,
MetadataReader reader,
bool ignoreCase,
OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved)
{
_process = process;
_module = module;
_reader = reader;
_stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
_ignoreCase = ignoreCase;
_onFunctionResolved = onFunctionResolved;
}
internal void Resolve(TRequest request, RequestSignature signature)
{
QualifiedName qualifiedTypeName;
ImmutableArray<string> memberTypeParameters;
GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters);
var typeName = qualifiedTypeName.Qualifier;
var memberName = qualifiedTypeName.Name;
var memberParameters = signature.Parameters;
var allTypeParameters = GetAllGenericTypeParameters(typeName);
foreach (var typeHandle in _reader.TypeDefinitions)
{
var typeDef = _reader.GetTypeDefinition(typeHandle);
int containingArity = CompareToTypeDefinition(typeDef, typeName);
if (containingArity < 0)
{
continue;
}
// Visit methods.
foreach (var methodHandle in typeDef.GetMethods())
{
var methodDef = _reader.GetMethodDefinition(methodHandle);
if (!IsResolvableMethod(methodDef))
{
continue;
}
if (MatchesMethod(typeDef, methodDef, typeName, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters))
{
OnFunctionResolved(request, methodHandle);
}
}
if (memberTypeParameters.IsEmpty)
{
// Visit properties.
foreach (var propertyHandle in typeDef.GetProperties())
{
var propertyDef = _reader.GetPropertyDefinition(propertyHandle);
if (MatchesProperty(typeDef, propertyDef, typeName, memberName, allTypeParameters, containingArity, memberParameters))
{
var accessors = propertyDef.GetAccessors();
OnAccessorResolved(request, accessors.Getter);
OnAccessorResolved(request, accessors.Setter);
}
}
}
}
}
// If the signature matches the TypeDefinition, including some or all containing
// types and namespaces, returns a non-negative value indicating the arity of the
// containing types that were not specified in the signature; otherwise returns -1.
// For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D,
// where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1
// is the arity of the containing types A<T>.B that were missing from the signature.
// "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire
// signature, from nested TypeDefinition, out.
private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature)
{
if (signature == null)
{
return typeDef.GetGenericParameters().Count;
}
QualifiedName qualifiedName;
ImmutableArray<string> typeParameters;
GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters);
if (!MatchesTypeName(typeDef, qualifiedName.Name))
{
return -1;
}
var declaringTypeHandle = typeDef.GetDeclaringType();
var declaringType = declaringTypeHandle.IsNil ? default(TypeDefinition) : _reader.GetTypeDefinition(declaringTypeHandle);
int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count;
if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount))
{
return -1;
}
var qualifier = qualifiedName.Qualifier;
if (declaringTypeHandle.IsNil)
{
// Compare namespace.
return MatchesNamespace(typeDef, qualifier) ? 0 : -1;
}
else
{
// Compare declaring type.
return CompareToTypeDefinition(declaringType, qualifier);
}
}
private bool MatchesNamespace(TypeDefinition typeDef, Name signature)
{
if (signature == null)
{
return true;
}
var namespaceName = _reader.GetString(typeDef.Namespace);
if (string.IsNullOrEmpty(namespaceName))
{
return false;
}
var parts = namespaceName.Split('.');
for (int index = parts.Length - 1; index >= 0; index--)
{
if (signature == null)
{
return true;
}
var qualifiedName = signature as QualifiedName;
if (qualifiedName == null)
{
return false;
}
var part = parts[index];
if (!_stringComparer.Equals(qualifiedName.Name, part))
{
return false;
}
signature = qualifiedName.Qualifier;
}
return signature == null;
}
private bool MatchesTypeName(TypeDefinition typeDef, string name)
{
var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name));
return _stringComparer.Equals(typeName, name);
}
private bool MatchesMethod(
TypeDefinition typeDef,
MethodDefinition methodDef,
Name typeName,
string methodName,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<string> methodTypeParameters,
ImmutableArray<ParameterSignature> methodParameters)
{
if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0)
{
if (!_reader.StringComparer.Equals(methodDef.Name, ".ctor", ignoreCase: false))
{
// Unhandled special name.
return false;
}
if (!MatchesTypeName(typeDef, methodName))
{
return false;
}
}
else if (!_reader.StringComparer.Equals(methodDef.Name, methodName, _ignoreCase))
{
return false;
}
if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0))
{
return false;
}
if (methodParameters.IsDefault)
{
return true;
}
return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters);
}
private bool MatchesProperty(
TypeDefinition typeDef,
PropertyDefinition propertyDef,
Name typeName,
string propertyName,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<ParameterSignature> propertyParameters)
{
if (!_reader.StringComparer.Equals(propertyDef.Name, propertyName, _ignoreCase))
{
return false;
}
if (propertyParameters.IsDefault)
{
return true;
}
if (propertyParameters.Length == 0)
{
// Parameter-less properties should be specified
// with no parameter list.
return false;
}
// Match parameters against getter. Not supporting
// matching against setter for write-only properties.
var methodHandle = propertyDef.GetAccessors().Getter;
if (methodHandle.IsNil)
{
return false;
}
var methodDef = _reader.GetMethodDefinition(methodHandle);
return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters);
}
private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName)
{
var builder = ImmutableArray.CreateBuilder<string>();
GetAllGenericTypeParameters(typeName, builder);
return builder.ToImmutable();
}
private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder)
{
if (typeName == null)
{
return;
}
QualifiedName qualifiedName;
ImmutableArray<string> typeParameters;
GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters);
GetAllGenericTypeParameters(qualifiedName.Qualifier, builder);
builder.AddRange(typeParameters);
}
private bool MatchesParameters(
MethodDefinition methodDef,
ImmutableArray<string> allTypeParameters,
int containingArity,
ImmutableArray<string> methodTypeParameters,
ImmutableArray<ParameterSignature> methodParameters)
{
ImmutableArray<ParameterSignature> parameters;
try
{
var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters);
parameters = decoder.DecodeParameters(methodDef);
}
catch (NotSupportedException)
{
return false;
}
catch (BadImageFormatException)
{
return false;
}
return methodParameters.SequenceEqual(parameters, MatchesParameter);
}
private void OnFunctionResolved(
TRequest request,
MethodDefinitionHandle handle)
{
Debug.Assert(!handle.IsNil);
_onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0);
}
private void OnAccessorResolved(
TRequest request,
MethodDefinitionHandle handle)
{
if (handle.IsNil)
{
return;
}
var methodDef = _reader.GetMethodDefinition(handle);
if (IsResolvableMethod(methodDef))
{
OnFunctionResolved(request, handle);
}
}
private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset)
{
return typeArguments.Length == typeParameters.Count - offset;
}
// parameterA from string signature, parameterB from metadata.
private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB)
{
return MatchesType(parameterA.Type, parameterB.Type) &&
parameterA.IsByRef == parameterB.IsByRef;
}
// typeA from string signature, typeB from metadata.
private bool MatchesType(TypeSignature typeA, TypeSignature typeB)
{
if (typeA.Kind != typeB.Kind)
{
return false;
}
switch (typeA.Kind)
{
case TypeSignatureKind.GenericType:
{
var genericA = (GenericTypeSignature)typeA;
var genericB = (GenericTypeSignature)typeB;
return MatchesType(genericA.QualifiedName, genericB.QualifiedName) &&
genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType);
}
case TypeSignatureKind.QualifiedType:
{
var qualifiedA = (QualifiedTypeSignature)typeA;
var qualifiedB = (QualifiedTypeSignature)typeB;
// Metadata signature may be more qualified than the
// string signature but still considered a match
// (e.g.: "B<U>.C" should match N.A<T>.B<U>.C).
return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) &&
_stringComparer.Equals(qualifiedA.Name, qualifiedB.Name);
}
case TypeSignatureKind.ArrayType:
{
var arrayA = (ArrayTypeSignature)typeA;
var arrayB = (ArrayTypeSignature)typeB;
return MatchesType(arrayA.ElementType, arrayB.ElementType) &&
arrayA.Rank == arrayB.Rank;
}
case TypeSignatureKind.PointerType:
{
var pointerA = (PointerTypeSignature)typeA;
var pointerB = (PointerTypeSignature)typeB;
return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType);
}
default:
throw ExceptionUtilities.UnexpectedValue(typeA.Kind);
}
}
private static void GetNameAndTypeParameters(
Name name,
out QualifiedName qualifiedName,
out ImmutableArray<string> typeParameters)
{
switch (name.Kind)
{
case NameKind.GenericName:
{
var genericName = (GenericName)name;
qualifiedName = genericName.QualifiedName;
typeParameters = genericName.TypeParameters;
}
break;
case NameKind.QualifiedName:
{
qualifiedName = (QualifiedName)name;
typeParameters = ImmutableArray<string>.Empty;
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(name.Kind);
}
}
private static bool IsResolvableMethod(MethodDefinition methodDef)
{
return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0;
}
private static string RemoveAritySeparatorIfAny(string typeName)
{
int index = typeName.LastIndexOf('`');
return (index < 0) ? typeName : typeName.Substring(0, index);
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/ChangeSignature/Parameter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
/// <summary>
/// Base type for Parameter information, whether the parameter
/// is preexisting or new.
/// </summary>
internal abstract class Parameter
{
public abstract bool HasDefaultValue { get; }
public abstract string Name { get; }
}
internal sealed class ExistingParameter : Parameter
{
public IParameterSymbol Symbol { get; }
public ExistingParameter(IParameterSymbol param)
{
Symbol = param;
}
public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue;
public override string Name => Symbol.Name;
}
internal sealed class AddedParameter : Parameter
{
public AddedParameter(
ITypeSymbol type,
string typeName,
string name,
CallSiteKind callSiteKind,
string callSiteValue = "",
bool isRequired = true,
string defaultValue = "",
bool typeBinds = true)
{
Type = type;
TypeBinds = typeBinds;
TypeName = typeName;
Name = name;
CallSiteValue = callSiteValue;
IsRequired = isRequired;
DefaultValue = defaultValue;
CallSiteKind = callSiteKind;
// Populate the call site text for the UI
switch (CallSiteKind)
{
case CallSiteKind.Value:
case CallSiteKind.ValueWithName:
CallSiteValue = callSiteValue;
break;
case CallSiteKind.Todo:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable;
break;
case CallSiteKind.Omitted:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue;
break;
case CallSiteKind.Inferred:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue;
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
public override string Name { get; }
public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue);
public ITypeSymbol Type { get; }
public string TypeName { get; }
public bool TypeBinds { get; }
public CallSiteKind CallSiteKind { get; }
/// <summary>
/// Display string for the Call Site column in the Change Signature dialog.
/// </summary>
public string CallSiteValue { get; }
/// <summary>
/// True if required, false if optional with a default value.
/// </summary>
public bool IsRequired { get; }
/// <summary>
/// Value to use in the declaration of an optional parameter.
/// E.g. the "3" in M(int x = 3);
/// </summary>
public string DefaultValue { get; }
// For test purposes: to display assert failure details in tests.
public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
/// <summary>
/// Base type for Parameter information, whether the parameter
/// is preexisting or new.
/// </summary>
internal abstract class Parameter
{
public abstract bool HasDefaultValue { get; }
public abstract string Name { get; }
}
internal sealed class ExistingParameter : Parameter
{
public IParameterSymbol Symbol { get; }
public ExistingParameter(IParameterSymbol param)
{
Symbol = param;
}
public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue;
public override string Name => Symbol.Name;
}
internal sealed class AddedParameter : Parameter
{
public AddedParameter(
ITypeSymbol type,
string typeName,
string name,
CallSiteKind callSiteKind,
string callSiteValue = "",
bool isRequired = true,
string defaultValue = "",
bool typeBinds = true)
{
Type = type;
TypeBinds = typeBinds;
TypeName = typeName;
Name = name;
CallSiteValue = callSiteValue;
IsRequired = isRequired;
DefaultValue = defaultValue;
CallSiteKind = callSiteKind;
// Populate the call site text for the UI
switch (CallSiteKind)
{
case CallSiteKind.Value:
case CallSiteKind.ValueWithName:
CallSiteValue = callSiteValue;
break;
case CallSiteKind.Todo:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable;
break;
case CallSiteKind.Omitted:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue;
break;
case CallSiteKind.Inferred:
CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue;
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
public override string Name { get; }
public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue);
public ITypeSymbol Type { get; }
public string TypeName { get; }
public bool TypeBinds { get; }
public CallSiteKind CallSiteKind { get; }
/// <summary>
/// Display string for the Call Site column in the Change Signature dialog.
/// </summary>
public string CallSiteValue { get; }
/// <summary>
/// True if required, false if optional with a default value.
/// </summary>
public bool IsRequired { get; }
/// <summary>
/// Value to use in the declaration of an optional parameter.
/// E.g. the "3" in M(int x = 3);
/// </summary>
public string DefaultValue { get; }
// For test purposes: to display assert failure details in tests.
public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})";
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/CodeGen/SequencePointList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Maintains a list of sequence points in a space efficient way. Most of the time sequence points
/// occur in the same syntax tree, so optimize for that case. Store a sequence point as an offset, and
/// position in a syntax tree, then translate to CCI format only on demand.
///
/// Use a ArrayBuilder{RawSequencePoint} to create.
/// </summary>
internal class SequencePointList
{
private readonly SyntaxTree _tree;
private readonly OffsetAndSpan[] _points;
private SequencePointList _next; // Linked list of all points.
// No sequence points.
private static readonly SequencePointList s_empty = new SequencePointList();
// Construct a list with no sequence points.
private SequencePointList()
{
_points = Array.Empty<OffsetAndSpan>();
}
// Construct a list with sequence points from exactly one syntax tree.
private SequencePointList(SyntaxTree tree, OffsetAndSpan[] points)
{
_tree = tree;
_points = points;
}
/// <summary>
/// Create a SequencePointList with the raw sequence points from an ArrayBuilder.
/// A linked list of instances for each syntax tree is created (almost always of length one).
/// </summary>
public static SequencePointList Create(ArrayBuilder<RawSequencePoint> seqPointBuilder, ILBuilder builder)
{
if (seqPointBuilder.Count == 0)
{
return SequencePointList.s_empty;
}
SequencePointList first = null, current = null;
int totalPoints = seqPointBuilder.Count;
int last = 0;
for (int i = 1; i <= totalPoints; ++i)
{
if (i == totalPoints || seqPointBuilder[i].SyntaxTree != seqPointBuilder[i - 1].SyntaxTree)
{
// Create a new list
SequencePointList next = new SequencePointList(seqPointBuilder[i - 1].SyntaxTree, GetSubArray(seqPointBuilder, last, i - last, builder));
last = i;
// Link together with any additional.
if (current == null)
{
first = current = next;
}
else
{
current._next = next;
current = next;
}
}
}
return first;
}
public bool IsEmpty
{
get
{
return _next == null && _points.Length == 0;
}
}
private static OffsetAndSpan[] GetSubArray(ArrayBuilder<RawSequencePoint> seqPointBuilder, int start, int length, ILBuilder builder)
{
OffsetAndSpan[] result = new OffsetAndSpan[length];
for (int i = 0; i < result.Length; i++)
{
RawSequencePoint point = seqPointBuilder[i + start];
int ilOffset = builder.GetILOffsetFromMarker(point.ILMarker);
Debug.Assert(ilOffset >= 0);
result[i] = new OffsetAndSpan(ilOffset, point.Span);
}
return result;
}
/// <summary>
/// Get all the sequence points, possibly mapping them using #line/ExternalSource directives, and mapping
/// file names to debug documents with the given mapping function.
/// </summary>
/// <param name="documentProvider">Function that maps file paths to CCI debug documents</param>
/// <param name="builder">where sequence points should be deposited</param>
public void GetSequencePoints(
DebugDocumentProvider documentProvider,
ArrayBuilder<Cci.SequencePoint> builder)
{
bool lastPathIsMapped = false;
string lastPath = null;
Cci.DebugSourceDocument lastDebugDocument = null;
FileLinePositionSpan? firstReal = FindFirstRealSequencePoint();
if (!firstReal.HasValue)
{
return;
}
lastPath = firstReal.Value.Path;
lastPathIsMapped = firstReal.Value.HasMappedPath;
lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? this._tree.FilePath : null);
SequencePointList current = this;
while (current != null)
{
SyntaxTree currentTree = current._tree;
foreach (var offsetAndSpan in current._points)
{
TextSpan span = offsetAndSpan.Span;
// if it's a hidden sequence point, or a sequence point with syntax that points to a position that is inside
// of a hidden region (can be defined with #line hidden (C#) or implicitly by #ExternalSource (VB), make it
// a hidden sequence point.
bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan;
FileLinePositionSpan fileLinePositionSpan = default;
if (!isHidden)
{
fileLinePositionSpan = currentTree.GetMappedLineSpanAndVisibility(span, out isHidden);
}
if (isHidden)
{
if (lastPath == null)
{
lastPath = currentTree.FilePath;
lastDebugDocument = documentProvider(lastPath, basePath: null);
}
if (lastDebugDocument != null)
{
builder.Add(new Cci.SequencePoint(
lastDebugDocument,
offset: offsetAndSpan.Offset,
startLine: Cci.SequencePoint.HiddenLine,
startColumn: 0,
endLine: Cci.SequencePoint.HiddenLine,
endColumn: 0));
}
}
else
{
if (lastPath != fileLinePositionSpan.Path || lastPathIsMapped != fileLinePositionSpan.HasMappedPath)
{
lastPath = fileLinePositionSpan.Path;
lastPathIsMapped = fileLinePositionSpan.HasMappedPath;
lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? currentTree.FilePath : null);
}
if (lastDebugDocument != null)
{
int startLine = (fileLinePositionSpan.StartLinePosition.Line == -1) ? 0 : fileLinePositionSpan.StartLinePosition.Line + 1;
int endLine = (fileLinePositionSpan.EndLinePosition.Line == -1) ? 0 : fileLinePositionSpan.EndLinePosition.Line + 1;
int startColumn = fileLinePositionSpan.StartLinePosition.Character + 1;
int endColumn = fileLinePositionSpan.EndLinePosition.Character + 1;
// Trim column number if necessary.
// Column must be in range [0, 0xffff) and end column must be greater than start column if on the same line.
// The Portable PDB specifies 0x10000, but System.Reflection.Metadata reader has an off-by-one error.
// Windows PDBs allow the same range.
const int MaxColumn = ushort.MaxValue - 1;
if (startColumn > MaxColumn)
{
startColumn = (startLine == endLine) ? MaxColumn - 1 : MaxColumn;
}
if (endColumn > MaxColumn)
{
endColumn = MaxColumn;
}
builder.Add(new Cci.SequencePoint(
lastDebugDocument,
offset: offsetAndSpan.Offset,
startLine: startLine,
startColumn: (ushort)startColumn,
endLine: endLine,
endColumn: (ushort)endColumn
));
}
}
}
current = current._next;
}
}
// Find the document for the first non-hidden sequence point (issue #4370)
// Returns null if a real sequence point was not found.
private FileLinePositionSpan? FindFirstRealSequencePoint()
{
SequencePointList current = this;
while (current != null)
{
foreach (var offsetAndSpan in current._points)
{
TextSpan span = offsetAndSpan.Span;
bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan;
if (!isHidden)
{
FileLinePositionSpan fileLinePositionSpan = current._tree.GetMappedLineSpanAndVisibility(span, out isHidden);
if (!isHidden)
{
return fileLinePositionSpan;
}
}
}
current = current._next;
}
return null;
}
/// <summary>
/// Represents the combination of an IL offset and a source text span.
/// </summary>
private struct OffsetAndSpan
{
public readonly int Offset;
public readonly TextSpan Span;
public OffsetAndSpan(int offset, TextSpan span)
{
this.Offset = offset;
this.Span = 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.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Maintains a list of sequence points in a space efficient way. Most of the time sequence points
/// occur in the same syntax tree, so optimize for that case. Store a sequence point as an offset, and
/// position in a syntax tree, then translate to CCI format only on demand.
///
/// Use a ArrayBuilder{RawSequencePoint} to create.
/// </summary>
internal class SequencePointList
{
private readonly SyntaxTree _tree;
private readonly OffsetAndSpan[] _points;
private SequencePointList _next; // Linked list of all points.
// No sequence points.
private static readonly SequencePointList s_empty = new SequencePointList();
// Construct a list with no sequence points.
private SequencePointList()
{
_points = Array.Empty<OffsetAndSpan>();
}
// Construct a list with sequence points from exactly one syntax tree.
private SequencePointList(SyntaxTree tree, OffsetAndSpan[] points)
{
_tree = tree;
_points = points;
}
/// <summary>
/// Create a SequencePointList with the raw sequence points from an ArrayBuilder.
/// A linked list of instances for each syntax tree is created (almost always of length one).
/// </summary>
public static SequencePointList Create(ArrayBuilder<RawSequencePoint> seqPointBuilder, ILBuilder builder)
{
if (seqPointBuilder.Count == 0)
{
return SequencePointList.s_empty;
}
SequencePointList first = null, current = null;
int totalPoints = seqPointBuilder.Count;
int last = 0;
for (int i = 1; i <= totalPoints; ++i)
{
if (i == totalPoints || seqPointBuilder[i].SyntaxTree != seqPointBuilder[i - 1].SyntaxTree)
{
// Create a new list
SequencePointList next = new SequencePointList(seqPointBuilder[i - 1].SyntaxTree, GetSubArray(seqPointBuilder, last, i - last, builder));
last = i;
// Link together with any additional.
if (current == null)
{
first = current = next;
}
else
{
current._next = next;
current = next;
}
}
}
return first;
}
public bool IsEmpty
{
get
{
return _next == null && _points.Length == 0;
}
}
private static OffsetAndSpan[] GetSubArray(ArrayBuilder<RawSequencePoint> seqPointBuilder, int start, int length, ILBuilder builder)
{
OffsetAndSpan[] result = new OffsetAndSpan[length];
for (int i = 0; i < result.Length; i++)
{
RawSequencePoint point = seqPointBuilder[i + start];
int ilOffset = builder.GetILOffsetFromMarker(point.ILMarker);
Debug.Assert(ilOffset >= 0);
result[i] = new OffsetAndSpan(ilOffset, point.Span);
}
return result;
}
/// <summary>
/// Get all the sequence points, possibly mapping them using #line/ExternalSource directives, and mapping
/// file names to debug documents with the given mapping function.
/// </summary>
/// <param name="documentProvider">Function that maps file paths to CCI debug documents</param>
/// <param name="builder">where sequence points should be deposited</param>
public void GetSequencePoints(
DebugDocumentProvider documentProvider,
ArrayBuilder<Cci.SequencePoint> builder)
{
bool lastPathIsMapped = false;
string lastPath = null;
Cci.DebugSourceDocument lastDebugDocument = null;
FileLinePositionSpan? firstReal = FindFirstRealSequencePoint();
if (!firstReal.HasValue)
{
return;
}
lastPath = firstReal.Value.Path;
lastPathIsMapped = firstReal.Value.HasMappedPath;
lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? this._tree.FilePath : null);
SequencePointList current = this;
while (current != null)
{
SyntaxTree currentTree = current._tree;
foreach (var offsetAndSpan in current._points)
{
TextSpan span = offsetAndSpan.Span;
// if it's a hidden sequence point, or a sequence point with syntax that points to a position that is inside
// of a hidden region (can be defined with #line hidden (C#) or implicitly by #ExternalSource (VB), make it
// a hidden sequence point.
bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan;
FileLinePositionSpan fileLinePositionSpan = default;
if (!isHidden)
{
fileLinePositionSpan = currentTree.GetMappedLineSpanAndVisibility(span, out isHidden);
}
if (isHidden)
{
if (lastPath == null)
{
lastPath = currentTree.FilePath;
lastDebugDocument = documentProvider(lastPath, basePath: null);
}
if (lastDebugDocument != null)
{
builder.Add(new Cci.SequencePoint(
lastDebugDocument,
offset: offsetAndSpan.Offset,
startLine: Cci.SequencePoint.HiddenLine,
startColumn: 0,
endLine: Cci.SequencePoint.HiddenLine,
endColumn: 0));
}
}
else
{
if (lastPath != fileLinePositionSpan.Path || lastPathIsMapped != fileLinePositionSpan.HasMappedPath)
{
lastPath = fileLinePositionSpan.Path;
lastPathIsMapped = fileLinePositionSpan.HasMappedPath;
lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? currentTree.FilePath : null);
}
if (lastDebugDocument != null)
{
int startLine = (fileLinePositionSpan.StartLinePosition.Line == -1) ? 0 : fileLinePositionSpan.StartLinePosition.Line + 1;
int endLine = (fileLinePositionSpan.EndLinePosition.Line == -1) ? 0 : fileLinePositionSpan.EndLinePosition.Line + 1;
int startColumn = fileLinePositionSpan.StartLinePosition.Character + 1;
int endColumn = fileLinePositionSpan.EndLinePosition.Character + 1;
// Trim column number if necessary.
// Column must be in range [0, 0xffff) and end column must be greater than start column if on the same line.
// The Portable PDB specifies 0x10000, but System.Reflection.Metadata reader has an off-by-one error.
// Windows PDBs allow the same range.
const int MaxColumn = ushort.MaxValue - 1;
if (startColumn > MaxColumn)
{
startColumn = (startLine == endLine) ? MaxColumn - 1 : MaxColumn;
}
if (endColumn > MaxColumn)
{
endColumn = MaxColumn;
}
builder.Add(new Cci.SequencePoint(
lastDebugDocument,
offset: offsetAndSpan.Offset,
startLine: startLine,
startColumn: (ushort)startColumn,
endLine: endLine,
endColumn: (ushort)endColumn
));
}
}
}
current = current._next;
}
}
// Find the document for the first non-hidden sequence point (issue #4370)
// Returns null if a real sequence point was not found.
private FileLinePositionSpan? FindFirstRealSequencePoint()
{
SequencePointList current = this;
while (current != null)
{
foreach (var offsetAndSpan in current._points)
{
TextSpan span = offsetAndSpan.Span;
bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan;
if (!isHidden)
{
FileLinePositionSpan fileLinePositionSpan = current._tree.GetMappedLineSpanAndVisibility(span, out isHidden);
if (!isHidden)
{
return fileLinePositionSpan;
}
}
}
current = current._next;
}
return null;
}
/// <summary>
/// Represents the combination of an IL offset and a source text span.
/// </summary>
private struct OffsetAndSpan
{
public readonly int Offset;
public readonly TextSpan Span;
public OffsetAndSpan(int offset, TextSpan span)
{
this.Offset = offset;
this.Span = span;
}
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./docs/README.md | README
======
This file is a placeholder. This directory will contain public documentation. | README
======
This file is a placeholder. This directory will contain public documentation. | -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Symbols/Attributes/EarlyDecodeWellKnownAttributeArguments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Contains common arguments to Symbol.EarlyDecodeWellKnownAttribute method in both the language compilers.
/// </summary>
internal struct EarlyDecodeWellKnownAttributeArguments<TEarlyBinder, TNamedTypeSymbol, TAttributeSyntax, TAttributeLocation>
where TNamedTypeSymbol : INamedTypeSymbolInternal
where TAttributeSyntax : SyntaxNode
{
/// <summary>
/// Object to store the decoded data from early bound well-known attributes.
/// Created lazily only when some decoded data needs to be stored, null otherwise.
/// </summary>
private EarlyWellKnownAttributeData _lazyDecodeData;
/// <summary>
/// Gets or creates the decoded data object.
/// </summary>
/// <remarks>
/// This method must be called only when some decoded data will be stored into it subsequently.
/// </remarks>
public T GetOrCreateData<T>() where T : EarlyWellKnownAttributeData, new()
{
if (_lazyDecodeData == null)
{
_lazyDecodeData = new T();
}
return (T)_lazyDecodeData;
}
/// <summary>
/// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>.
/// </summary>
public bool HasDecodedData
{
get
{
if (_lazyDecodeData != null)
{
_lazyDecodeData.VerifyDataStored(expected: true);
return true;
}
return false;
}
}
/// <summary>
/// Gets the stored decoded data.
/// </summary>
/// <remarks>
/// Assumes <see cref="HasDecodedData"/> is true.
/// </remarks>
public EarlyWellKnownAttributeData DecodedData
{
get
{
Debug.Assert(this.HasDecodedData);
return _lazyDecodeData;
}
}
/// <summary>
/// Binder to bind early well-known attributes.
/// </summary>
public TEarlyBinder Binder { get; set; }
/// <summary>
/// Bound type of the attribute to decode.
/// </summary>
public TNamedTypeSymbol AttributeType { get; set; }
/// <summary>
/// Syntax of the attribute to decode.
/// </summary>
public TAttributeSyntax AttributeSyntax { get; set; }
/// <summary>
/// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself.
/// Used e.g. for return type attributes of a method symbol.
/// </summary>
public TAttributeLocation SymbolPart { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Contains common arguments to Symbol.EarlyDecodeWellKnownAttribute method in both the language compilers.
/// </summary>
internal struct EarlyDecodeWellKnownAttributeArguments<TEarlyBinder, TNamedTypeSymbol, TAttributeSyntax, TAttributeLocation>
where TNamedTypeSymbol : INamedTypeSymbolInternal
where TAttributeSyntax : SyntaxNode
{
/// <summary>
/// Object to store the decoded data from early bound well-known attributes.
/// Created lazily only when some decoded data needs to be stored, null otherwise.
/// </summary>
private EarlyWellKnownAttributeData _lazyDecodeData;
/// <summary>
/// Gets or creates the decoded data object.
/// </summary>
/// <remarks>
/// This method must be called only when some decoded data will be stored into it subsequently.
/// </remarks>
public T GetOrCreateData<T>() where T : EarlyWellKnownAttributeData, new()
{
if (_lazyDecodeData == null)
{
_lazyDecodeData = new T();
}
return (T)_lazyDecodeData;
}
/// <summary>
/// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>.
/// </summary>
public bool HasDecodedData
{
get
{
if (_lazyDecodeData != null)
{
_lazyDecodeData.VerifyDataStored(expected: true);
return true;
}
return false;
}
}
/// <summary>
/// Gets the stored decoded data.
/// </summary>
/// <remarks>
/// Assumes <see cref="HasDecodedData"/> is true.
/// </remarks>
public EarlyWellKnownAttributeData DecodedData
{
get
{
Debug.Assert(this.HasDecodedData);
return _lazyDecodeData;
}
}
/// <summary>
/// Binder to bind early well-known attributes.
/// </summary>
public TEarlyBinder Binder { get; set; }
/// <summary>
/// Bound type of the attribute to decode.
/// </summary>
public TNamedTypeSymbol AttributeType { get; set; }
/// <summary>
/// Syntax of the attribute to decode.
/// </summary>
public TAttributeSyntax AttributeSyntax { get; set; }
/// <summary>
/// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself.
/// Used e.g. for return type attributes of a method symbol.
/// </summary>
public TAttributeLocation SymbolPart { get; set; }
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.cs.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../Resources.resx">
<body>
<trans-unit id="CanNotCreateWindow">
<source>Can not create tool window.</source>
<target state="translated">Nejde vytvořit okno nástroje.</target>
<note />
</trans-unit>
<trans-unit id="ToolWindowTitle">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnostika Roslyn</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../Resources.resx">
<body>
<trans-unit id="CanNotCreateWindow">
<source>Can not create tool window.</source>
<target state="translated">Nejde vytvořit okno nástroje.</target>
<note />
</trans-unit>
<trans-unit id="ToolWindowTitle">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnostika Roslyn</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Extensions/SnapshotSpanExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions
{
internal static class SnapshotSpanExtensions
{
public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan)
{
snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex);
return new VsTextSpan()
{
iStartLine = startLine,
iStartIndex = startCharacterIndex,
iEndLine = endLine,
iEndIndex = endCharacterIndex
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions
{
internal static class SnapshotSpanExtensions
{
public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan)
{
snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex);
return new VsTextSpan()
{
iStartLine = startLine,
iStartIndex = startCharacterIndex,
iEndLine = endLine,
iEndIndex = endCharacterIndex
};
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source4Module.netmodule | MZ @ !L!This program cannot be run in DOS mode.
$ PE L )L " @ @ ` @ ! S @ H .text `.reloc @ @ B ! H X ` (
*BSJB v4.0.30319 l #~ D #Strings 8 #US @ #GUID P #Blob G %3 * P $
$
<Module> mscorlib C4 System Object .ctor Source4Module.netmodule ?EK;VG'= z\V4 ! ! ! _CorExeMain mscoree.dll % @ 2 | MZ @ !L!This program cannot be run in DOS mode.
$ PE L )L " @ @ ` @ ! S @ H .text `.reloc @ @ B ! H X ` (
*BSJB v4.0.30319 l #~ D #Strings 8 #US @ #GUID P #Blob G %3 * P $
$
<Module> mscorlib C4 System Object .ctor Source4Module.netmodule ?EK;VG'= z\V4 ! ! ! _CorExeMain mscoree.dll % @ 2 | -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Projekt wird erstellt</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">Fehler beim Umbenennen: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktive Hostprozessplattform</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target>
<note />
</trans-unit>
<trans-unit id="Regex_Comment">
<source>Regex - Comment</source>
<target state="translated">RegEx - Kommentar</target>
<note />
</trans-unit>
<trans-unit id="Regex_Character_Class">
<source>Regex - Character Class</source>
<target state="translated">RegEx - Zeichenklasse</target>
<note />
</trans-unit>
<trans-unit id="Regex_Alternation">
<source>Regex - Alternation</source>
<target state="translated">RegEx - Wechsel</target>
<note />
</trans-unit>
<trans-unit id="Regex_Anchor">
<source>Regex - Anchor</source>
<target state="translated">RegEx - Anker</target>
<note />
</trans-unit>
<trans-unit id="Regex_Quantifier">
<source>Regex - Quantifier</source>
<target state="translated">RegEx - Quantifizierer</target>
<note />
</trans-unit>
<trans-unit id="Regex_SelfEscapedCharacter">
<source>Regex - Self Escaped Character</source>
<target state="translated">RegEx - Selbstständiges Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Regex_Grouping">
<source>Regex - Grouping</source>
<target state="translated">RegEx - Gruppierung</target>
<note />
</trans-unit>
<trans-unit id="Regex_Text">
<source>Regex - Text</source>
<target state="translated">RegEx - Text</target>
<note />
</trans-unit>
<trans-unit id="Regex_OtherEscape">
<source>Regex - Other Escape</source>
<target state="translated">RegEx - Anderes Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Interactives Element wird zurückgesetzt</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Projekt wird erstellt</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">Fehler beim Umbenennen: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktive Hostprozessplattform</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target>
<note />
</trans-unit>
<trans-unit id="Regex_Comment">
<source>Regex - Comment</source>
<target state="translated">RegEx - Kommentar</target>
<note />
</trans-unit>
<trans-unit id="Regex_Character_Class">
<source>Regex - Character Class</source>
<target state="translated">RegEx - Zeichenklasse</target>
<note />
</trans-unit>
<trans-unit id="Regex_Alternation">
<source>Regex - Alternation</source>
<target state="translated">RegEx - Wechsel</target>
<note />
</trans-unit>
<trans-unit id="Regex_Anchor">
<source>Regex - Anchor</source>
<target state="translated">RegEx - Anker</target>
<note />
</trans-unit>
<trans-unit id="Regex_Quantifier">
<source>Regex - Quantifier</source>
<target state="translated">RegEx - Quantifizierer</target>
<note />
</trans-unit>
<trans-unit id="Regex_SelfEscapedCharacter">
<source>Regex - Self Escaped Character</source>
<target state="translated">RegEx - Selbstständiges Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Regex_Grouping">
<source>Regex - Grouping</source>
<target state="translated">RegEx - Gruppierung</target>
<note />
</trans-unit>
<trans-unit id="Regex_Text">
<source>Regex - Text</source>
<target state="translated">RegEx - Text</target>
<note />
</trans-unit>
<trans-unit id="Regex_OtherEscape">
<source>Regex - Other Escape</source>
<target state="translated">RegEx - Anderes Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Interactives Element wird zurückgesetzt</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeRefactorings/AbstractRefactoringHelpersService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService
where TExpressionSyntax : SyntaxNode
where TArgumentSyntax : SyntaxNode
where TExpressionStatementSyntax : SyntaxNode
{
public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>(
Document document, TextSpan selectionRaw,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends
// at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing
// block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia
// (whitespace) of following statement.
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root == null)
{
return ImmutableArray<TSyntaxNode>.Empty;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false);
// If user selected only whitespace we don't want to return anything. We could do following:
// 1) Consider token that owns (as its trivia) the whitespace.
// 2) Consider start/beginning of whitespace as location (empty selection)
// Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the
// most consistent option.
if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty)
{
return ImmutableArray<TSyntaxNode>.Empty;
}
using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder);
// Every time a Node is considered an extractNodes method is called to add all nodes around the original one
// that should also be considered.
//
// That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially
// lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might
// want the whole node `var a = b;`
// Handle selections:
// - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]`
// - The smallest node whose FullSpan includes the whole (trimmed) selection
// - Using FullSpan is important because it handles over-selection with comments
// - Travels upwards through same-sized (FullSpan) nodes, extracting
// - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`)
// Note: Whether we have selection or location has to be checked against original selection because selecting just
// whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token`
// registering as ` [||]token`.
if (!selectionTrimmed.IsEmpty)
{
AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken);
}
else
{
// No more selection -> Handle what current selection is touching:
//
// Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as
// touching the Method's Node (through the left edge, see below) which is something the user probably
// didn't want since they specifically selected only the return type.
//
// What the selection is touching is used in two ways.
// - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node.
// While having the (even empty) selection inside such token or to left of such Token is already handle
// by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node).
// - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct
// ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to
// be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the
// Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially
// continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical.
// E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher
// node doesn't end on position anymore)
// Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information.
// - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in.
// more about that below.
// - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it
// as long as it is on the first line of such expression (arbitrary heuristic).
// First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft.
var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync(
document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false);
// In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level
// desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for
// Property Decl.
// We cannot check this any sooner because the above code could've changed current location.
AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken);
// Add Nodes for touching tokens as described above.
AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken);
AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken);
// If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode.
// We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in.
if (IsWantedTypeExpressionLike<TSyntaxNode>())
{
// Reason to treat Arguments (and potentially others) as Expression-like:
// https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904
await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false);
}
}
return relevantNodesBuilder.ToImmutable();
}
private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode
{
var wantedType = typeof(TSyntaxNode);
var expressionType = typeof(TExpressionSyntax);
var argumentType = typeof(TArgumentSyntax);
var expressionStatementType = typeof(TExpressionStatementSyntax);
return IsAEqualOrSubclassOfB(wantedType, expressionType) ||
IsAEqualOrSubclassOfB(wantedType, argumentType) ||
IsAEqualOrSubclassOfB(wantedType, expressionStatementType);
static bool IsAEqualOrSubclassOfB(Type a, Type b)
{
return a.IsSubclassOf(b) || a == b;
}
}
private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync(
Document document,
SyntaxNode root,
TextSpan selectionTrimmed,
CancellationToken cancellationToken)
{
// get Token for current location
var location = selectionTrimmed.Start;
var tokenOnLocation = root.FindToken(location);
// Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`)
var tokenToRightOrIn = tokenOnLocation.Span.Contains(location)
? tokenOnLocation
: default;
// A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location.
// Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`)
var tokenToLeft = default(SyntaxToken);
if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location)
{
var tokenPreLocation = (tokenOnLocation.Span.End == location)
? tokenOnLocation
: tokenOnLocation.GetPreviousToken(includeZeroWidth: true);
tokenToLeft = (tokenPreLocation.Span.End == location)
? tokenPreLocation
: default;
}
// If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace.
// Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically)
// closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was.
if (tokenToLeft == default && tokenToRightOrIn == default)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location))
{
// tokenOnLocation: token in whose trivia location is at
if (tokenOnLocation.Span.Start >= location)
{
tokenToRightOrIn = tokenOnLocation;
location = tokenToRightOrIn.Span.Start;
}
else
{
tokenToLeft = tokenOnLocation;
location = tokenToLeft.Span.End;
}
}
}
return (tokenToRightOrIn, tokenToLeft, location);
static bool IsAcceptableLineDistanceAway(
SourceText sourceText, SyntaxToken tokenOnLocation, int location)
{
// assume non-trivia token can't span multiple lines
var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start);
var locationLine = sourceText.Lines.GetLineFromPosition(location);
// Change location to nearest token only if the token is off by one line or less
var lineDistance = tokenLine.LineNumber - locationLine.LineNumber;
if (lineDistance is not 0 and not 1)
return false;
// Note: being a line below a tokenOnLocation is impossible in current model as whitespace
// trailing trivia ends on new line. Which is fine because if you're a line _after_ some node
// you usually don't want refactorings for what's above you.
if (lineDistance == 1)
{
// position is one line above the node of interest. This is fine if that
// line is blank. Otherwise, if it isn't (i.e. it contains comments,
// directives, or other trivia), then it's not likely the user is selecting
// this entry.
return locationLine.IsEmptyOrWhitespace();
}
// On hte same line. This position is acceptable.
return true;
}
}
private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them
while (tokenToLeft != default)
{
var leftNode = tokenToLeft.Parent!;
do
{
// Consider either a Node that is:
// - Ancestor Node of such Token as long as their span ends on location (it's still on the edge)
AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken);
leftNode = leftNode.Parent;
if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location))
{
break;
}
}
while (true);
// as long as current tokenToLeft is empty -> its previous token is also tokenToLeft
tokenToLeft = tokenToLeft.Span.IsEmpty
? tokenToLeft.GetPreviousToken(includeZeroWidth: true)
: default;
}
}
private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (tokenToRightOrIn != default)
{
var rightNode = tokenToRightOrIn.Parent!;
do
{
// Consider either a Node that is:
// - Parent of touched Token (location can be within)
// - Ancestor Node of such Token as long as their span starts on location (it's still on the edge)
AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken);
rightNode = rightNode.Parent;
if (rightNode == null)
{
break;
}
// The edge climbing for node to the right needs to handle Attributes e.g.:
// [Test1]
// //Comment1
// [||]object Property1 { get; set; }
// In essence:
// - On the left edge of the node (-> left edge of first AttributeLists)
// - On the left edge of the node sans AttributeLists (& as everywhere comments)
if (rightNode.Span.Start != location)
{
var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode);
if (rightNodeSpanWithoutAttributes.Start != location)
{
break;
}
}
}
while (true);
}
}
private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true);
var prevNode = selectionNode;
do
{
var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken));
foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes)
{
// For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`).
// In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it
// if user selected only its attributes.
// Selection contains only AttributeLists -> don't consider current Node
var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode);
if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes))
{
break;
}
relevantNodesBuilder.Add(nonHiddenExtractedNode);
}
prevNode = selectionNode;
selectionNode = selectionNode.Parent;
}
while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth());
}
/// <summary>
/// Extractor function that retrieves all nodes that should be considered for extraction of given current node.
/// <para>
/// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable
/// to provide refactoring for `b` node. Similarly for other types of refactorings.
/// </para>
/// </summary>
/// <remark>
/// Should also return given node.
/// </remark>
protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts)
{
if (node == null)
{
yield break;
}
// First return the node itself so that it is considered
yield return node;
// REMARKS:
// The set of currently attempted extractions is in no way exhaustive and covers only cases
// that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`.
// Feel free to extend it / refine current heuristics.
// `var a = b;` | `var a = b`;
if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent))
{
var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!;
// Check if there's only one variable being declared, otherwise following transformation
// would go through which isn't reasonable since we can't say the first one specifically
// is wanted.
// `var a = 1, `c = 2, d = 3`;
// -> `var a = 1`, c = 2, d = 3;
var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
if (variables.Count == 1)
{
var declaredVariable = variables.First();
// -> `a = b`
yield return declaredVariable;
// -> `b`
var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable);
if (initializer != null)
{
var value = syntaxFacts.GetValueOfEqualsValueClause(initializer);
if (value != null)
{
yield return value;
}
}
}
}
// var `a = b`;
if (syntaxFacts.IsVariableDeclarator(node))
{
// -> `b`
var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node);
if (initializer != null)
{
var value = syntaxFacts.GetValueOfEqualsValueClause(initializer);
if (value != null)
{
yield return value;
}
}
}
// `a = b;`
// -> `b`
if (syntaxFacts.IsSimpleAssignmentStatement(node))
{
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide);
yield return rightSide;
}
// `a();`
// -> a()
if (syntaxFacts.IsExpressionStatement(node))
{
yield return syntaxFacts.GetExpressionOfExpressionStatement(node);
}
// `a()`;
// -> `a();`
if (syntaxFacts.IsExpressionStatement(node.Parent))
{
yield return node.Parent;
}
}
/// <summary>
/// Extractor function that checks and retrieves all nodes current location is in a header.
/// </summary>
protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts)
{
// Header: [Test] `public int a` { get; set; }
if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration))
{
yield return propertyDeclaration;
}
// Header: public C([Test]`int a = 42`) {}
if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter))
{
yield return parameter;
}
// Header: `public I.C([Test]int a = 42)` {}
if (syntaxFacts.IsOnMethodHeader(root, location, out var method))
{
yield return method;
}
// Header: `static C([Test]int a = 42)` {}
if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction))
{
yield return localFunction;
}
// Header: `var a = `3,` b = `5,` c = `7 + 3``;
if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration))
{
yield return localDeclaration;
}
// Header: `if(...)`{ };
if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement))
{
yield return ifStatement;
}
// Header: `foreach (var a in b)` { }
if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement))
{
yield return foreachStatement;
}
if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration))
{
yield return typeDeclaration;
}
}
protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>(
Document document, int position,
ArrayBuilder<TSyntaxNode> relevantNodesBuilder,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync)
// -> can simply FindToken -> proceed testing its ancestors
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var token = root.FindTokenOnRightOfPosition(position, true);
// traverse upwards and add all parents if of correct type
var ancestor = token.Parent;
while (ancestor != null)
{
if (ancestor is TSyntaxNode correctTypeNode)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber;
var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber;
if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken))
{
relevantNodesBuilder.Add(correctTypeNode);
}
else if (argumentStartLine < caretLine)
{
// higher level nodes will have Span starting at least on the same line -> can bail out
return;
}
}
ancestor = ancestor.Parent;
}
}
private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken));
foreach (var nodeToBeAdded in correctTypeNonHiddenNodes)
{
resultBuilder.Add(nodeToBeAdded);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService
where TExpressionSyntax : SyntaxNode
where TArgumentSyntax : SyntaxNode
where TExpressionStatementSyntax : SyntaxNode
{
public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>(
Document document, TextSpan selectionRaw,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends
// at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing
// block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia
// (whitespace) of following statement.
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root == null)
{
return ImmutableArray<TSyntaxNode>.Empty;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false);
// If user selected only whitespace we don't want to return anything. We could do following:
// 1) Consider token that owns (as its trivia) the whitespace.
// 2) Consider start/beginning of whitespace as location (empty selection)
// Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the
// most consistent option.
if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty)
{
return ImmutableArray<TSyntaxNode>.Empty;
}
using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder);
// Every time a Node is considered an extractNodes method is called to add all nodes around the original one
// that should also be considered.
//
// That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially
// lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might
// want the whole node `var a = b;`
// Handle selections:
// - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]`
// - The smallest node whose FullSpan includes the whole (trimmed) selection
// - Using FullSpan is important because it handles over-selection with comments
// - Travels upwards through same-sized (FullSpan) nodes, extracting
// - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`)
// Note: Whether we have selection or location has to be checked against original selection because selecting just
// whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token`
// registering as ` [||]token`.
if (!selectionTrimmed.IsEmpty)
{
AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken);
}
else
{
// No more selection -> Handle what current selection is touching:
//
// Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as
// touching the Method's Node (through the left edge, see below) which is something the user probably
// didn't want since they specifically selected only the return type.
//
// What the selection is touching is used in two ways.
// - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node.
// While having the (even empty) selection inside such token or to left of such Token is already handle
// by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node).
// - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct
// ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to
// be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the
// Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially
// continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical.
// E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher
// node doesn't end on position anymore)
// Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information.
// - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in.
// more about that below.
// - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it
// as long as it is on the first line of such expression (arbitrary heuristic).
// First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft.
var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync(
document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false);
// In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level
// desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for
// Property Decl.
// We cannot check this any sooner because the above code could've changed current location.
AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken);
// Add Nodes for touching tokens as described above.
AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken);
AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken);
// If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode.
// We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in.
if (IsWantedTypeExpressionLike<TSyntaxNode>())
{
// Reason to treat Arguments (and potentially others) as Expression-like:
// https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904
await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false);
}
}
return relevantNodesBuilder.ToImmutable();
}
private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode
{
var wantedType = typeof(TSyntaxNode);
var expressionType = typeof(TExpressionSyntax);
var argumentType = typeof(TArgumentSyntax);
var expressionStatementType = typeof(TExpressionStatementSyntax);
return IsAEqualOrSubclassOfB(wantedType, expressionType) ||
IsAEqualOrSubclassOfB(wantedType, argumentType) ||
IsAEqualOrSubclassOfB(wantedType, expressionStatementType);
static bool IsAEqualOrSubclassOfB(Type a, Type b)
{
return a.IsSubclassOf(b) || a == b;
}
}
private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync(
Document document,
SyntaxNode root,
TextSpan selectionTrimmed,
CancellationToken cancellationToken)
{
// get Token for current location
var location = selectionTrimmed.Start;
var tokenOnLocation = root.FindToken(location);
// Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`)
var tokenToRightOrIn = tokenOnLocation.Span.Contains(location)
? tokenOnLocation
: default;
// A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location.
// Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`)
var tokenToLeft = default(SyntaxToken);
if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location)
{
var tokenPreLocation = (tokenOnLocation.Span.End == location)
? tokenOnLocation
: tokenOnLocation.GetPreviousToken(includeZeroWidth: true);
tokenToLeft = (tokenPreLocation.Span.End == location)
? tokenPreLocation
: default;
}
// If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace.
// Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically)
// closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was.
if (tokenToLeft == default && tokenToRightOrIn == default)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location))
{
// tokenOnLocation: token in whose trivia location is at
if (tokenOnLocation.Span.Start >= location)
{
tokenToRightOrIn = tokenOnLocation;
location = tokenToRightOrIn.Span.Start;
}
else
{
tokenToLeft = tokenOnLocation;
location = tokenToLeft.Span.End;
}
}
}
return (tokenToRightOrIn, tokenToLeft, location);
static bool IsAcceptableLineDistanceAway(
SourceText sourceText, SyntaxToken tokenOnLocation, int location)
{
// assume non-trivia token can't span multiple lines
var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start);
var locationLine = sourceText.Lines.GetLineFromPosition(location);
// Change location to nearest token only if the token is off by one line or less
var lineDistance = tokenLine.LineNumber - locationLine.LineNumber;
if (lineDistance is not 0 and not 1)
return false;
// Note: being a line below a tokenOnLocation is impossible in current model as whitespace
// trailing trivia ends on new line. Which is fine because if you're a line _after_ some node
// you usually don't want refactorings for what's above you.
if (lineDistance == 1)
{
// position is one line above the node of interest. This is fine if that
// line is blank. Otherwise, if it isn't (i.e. it contains comments,
// directives, or other trivia), then it's not likely the user is selecting
// this entry.
return locationLine.IsEmptyOrWhitespace();
}
// On hte same line. This position is acceptable.
return true;
}
}
private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them
while (tokenToLeft != default)
{
var leftNode = tokenToLeft.Parent!;
do
{
// Consider either a Node that is:
// - Ancestor Node of such Token as long as their span ends on location (it's still on the edge)
AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken);
leftNode = leftNode.Parent;
if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location))
{
break;
}
}
while (true);
// as long as current tokenToLeft is empty -> its previous token is also tokenToLeft
tokenToLeft = tokenToLeft.Span.IsEmpty
? tokenToLeft.GetPreviousToken(includeZeroWidth: true)
: default;
}
}
private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (tokenToRightOrIn != default)
{
var rightNode = tokenToRightOrIn.Parent!;
do
{
// Consider either a Node that is:
// - Parent of touched Token (location can be within)
// - Ancestor Node of such Token as long as their span starts on location (it's still on the edge)
AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken);
rightNode = rightNode.Parent;
if (rightNode == null)
{
break;
}
// The edge climbing for node to the right needs to handle Attributes e.g.:
// [Test1]
// //Comment1
// [||]object Property1 { get; set; }
// In essence:
// - On the left edge of the node (-> left edge of first AttributeLists)
// - On the left edge of the node sans AttributeLists (& as everywhere comments)
if (rightNode.Span.Start != location)
{
var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode);
if (rightNodeSpanWithoutAttributes.Start != location)
{
break;
}
}
}
while (true);
}
}
private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true);
var prevNode = selectionNode;
do
{
var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken));
foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes)
{
// For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`).
// In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it
// if user selected only its attributes.
// Selection contains only AttributeLists -> don't consider current Node
var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode);
if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes))
{
break;
}
relevantNodesBuilder.Add(nonHiddenExtractedNode);
}
prevNode = selectionNode;
selectionNode = selectionNode.Parent;
}
while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth());
}
/// <summary>
/// Extractor function that retrieves all nodes that should be considered for extraction of given current node.
/// <para>
/// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable
/// to provide refactoring for `b` node. Similarly for other types of refactorings.
/// </para>
/// </summary>
/// <remark>
/// Should also return given node.
/// </remark>
protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts)
{
if (node == null)
{
yield break;
}
// First return the node itself so that it is considered
yield return node;
// REMARKS:
// The set of currently attempted extractions is in no way exhaustive and covers only cases
// that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`.
// Feel free to extend it / refine current heuristics.
// `var a = b;` | `var a = b`;
if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent))
{
var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!;
// Check if there's only one variable being declared, otherwise following transformation
// would go through which isn't reasonable since we can't say the first one specifically
// is wanted.
// `var a = 1, `c = 2, d = 3`;
// -> `var a = 1`, c = 2, d = 3;
var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
if (variables.Count == 1)
{
var declaredVariable = variables.First();
// -> `a = b`
yield return declaredVariable;
// -> `b`
var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable);
if (initializer != null)
{
var value = syntaxFacts.GetValueOfEqualsValueClause(initializer);
if (value != null)
{
yield return value;
}
}
}
}
// var `a = b`;
if (syntaxFacts.IsVariableDeclarator(node))
{
// -> `b`
var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node);
if (initializer != null)
{
var value = syntaxFacts.GetValueOfEqualsValueClause(initializer);
if (value != null)
{
yield return value;
}
}
}
// `a = b;`
// -> `b`
if (syntaxFacts.IsSimpleAssignmentStatement(node))
{
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide);
yield return rightSide;
}
// `a();`
// -> a()
if (syntaxFacts.IsExpressionStatement(node))
{
yield return syntaxFacts.GetExpressionOfExpressionStatement(node);
}
// `a()`;
// -> `a();`
if (syntaxFacts.IsExpressionStatement(node.Parent))
{
yield return node.Parent;
}
}
/// <summary>
/// Extractor function that checks and retrieves all nodes current location is in a header.
/// </summary>
protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts)
{
// Header: [Test] `public int a` { get; set; }
if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration))
{
yield return propertyDeclaration;
}
// Header: public C([Test]`int a = 42`) {}
if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter))
{
yield return parameter;
}
// Header: `public I.C([Test]int a = 42)` {}
if (syntaxFacts.IsOnMethodHeader(root, location, out var method))
{
yield return method;
}
// Header: `static C([Test]int a = 42)` {}
if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction))
{
yield return localFunction;
}
// Header: `var a = `3,` b = `5,` c = `7 + 3``;
if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration))
{
yield return localDeclaration;
}
// Header: `if(...)`{ };
if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement))
{
yield return ifStatement;
}
// Header: `foreach (var a in b)` { }
if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement))
{
yield return foreachStatement;
}
if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration))
{
yield return typeDeclaration;
}
}
protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>(
Document document, int position,
ArrayBuilder<TSyntaxNode> relevantNodesBuilder,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
// If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync)
// -> can simply FindToken -> proceed testing its ancestors
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var token = root.FindTokenOnRightOfPosition(position, true);
// traverse upwards and add all parents if of correct type
var ancestor = token.Parent;
while (ancestor != null)
{
if (ancestor is TSyntaxNode correctTypeNode)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber;
var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber;
if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken))
{
relevantNodesBuilder.Add(correctTypeNode);
}
else if (argumentStartLine < caretLine)
{
// higher level nodes will have Span starting at least on the same line -> can bail out
return;
}
}
ancestor = ancestor.Parent;
}
}
private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken));
foreach (var nodeToBeAdded in correctTypeNonHiddenNodes)
{
resultBuilder.Add(nodeToBeAdded);
}
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ParamsKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ParamsKeywordRecommender()
: base(SyntaxKind.ParamsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ParamsKeywordRecommender()
: base(SyntaxKind.ParamsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken);
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Semantic/Compilation/SymbolSearchTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SymbolSearchTests
Inherits BasicTestBase
<Fact>
Public Sub TestSymbolFilterNone()
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(Function(n) True, SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(Function(n) True, SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName("", SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName("", SymbolFilter.None)
End Sub)
End Sub
<Fact>
Public Sub TestPredicateNull()
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(predicate:=Nothing)
End Sub)
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(predicate:=Nothing)
End Sub)
End Sub
<Fact>
Public Sub TestStringNull()
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(name:=Nothing)
End Sub)
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(name:=Nothing)
End Sub)
End Sub
<Fact>
Public Sub TestMergedNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestSourceNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestClassInMergedNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestClassInSourceNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestMembers()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=False, count:=0)
End Sub
<Fact>
Public Sub TestCaseInsensitivity()
Dim compilation = GetTestCompilation()
TestName(compilation, "system", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "mynamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "myfield", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
End Sub
<Fact>
Public Sub TestPartialSearch()
Dim compilation = GetTestCompilation()
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=False, includeMember:=True, count:=4)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=False, count:=4)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=True, count:=8)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=True, count:=5)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=False, count:=5)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=9)
TestPredicate(compilation, Function(n) n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=2)
End Sub
Private Shared Function GetTestCompilation() As VisualBasicCompilation
Dim source As String = <text>
Namespace System
Public Class Test
End Class
End Namespace
Namespace MyNamespace
Public Class Test1
End Class
End Namespace
Public Class [MyClass]
Private myField As Integer
Friend Property MyProperty As Integer
Sub MyMethod()
End Sub
Public Event MyEvent As EventHandler
Delegate Function MyDelegate(i As Integer) As String
End Class
Structure MyStruct
End Structure
Interface MyInterface
End Interface
Enum [Enum]
EnumValue
End Enum
</text>.Value
Return CreateCompilationWithMscorlib40({source})
End Function
Private Shared Sub TestNameAndPredicate(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
TestName(compilation, name, includeNamespace, includeType, includeMember, count)
TestPredicate(compilation, Function(n) n = name, includeNamespace, includeType, includeMember, count)
End Sub
Private Shared Sub TestName(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
Dim filter = ComputeFilter(includeNamespace, includeType, includeMember)
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter))
Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count())
End Sub
Private Shared Sub TestPredicate(compilation As VisualBasicCompilation, predicate As Func(Of String, Boolean), includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
Dim filter = ComputeFilter(includeNamespace, includeType, includeMember)
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter))
Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count())
End Sub
Private Shared Function ComputeFilter(includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean) As SymbolFilter
Dim filter = SymbolFilter.None
filter = If(includeNamespace, filter Or SymbolFilter.Namespace, filter)
filter = If(includeType, filter Or SymbolFilter.Type, filter)
filter = If(includeMember, filter Or SymbolFilter.Member, filter)
Return filter
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.
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SymbolSearchTests
Inherits BasicTestBase
<Fact>
Public Sub TestSymbolFilterNone()
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(Function(n) True, SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(Function(n) True, SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName("", SymbolFilter.None)
End Sub)
Assert.Throws(Of ArgumentException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName("", SymbolFilter.None)
End Sub)
End Sub
<Fact>
Public Sub TestPredicateNull()
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(predicate:=Nothing)
End Sub)
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(predicate:=Nothing)
End Sub)
End Sub
<Fact>
Public Sub TestStringNull()
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.ContainsSymbolsWithName(name:=Nothing)
End Sub)
Assert.Throws(Of ArgumentNullException)(Sub()
Dim compilation = GetTestCompilation()
compilation.GetSymbolsWithName(name:=Nothing)
End Sub)
End Sub
<Fact>
Public Sub TestMergedNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestSourceNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestClassInMergedNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestClassInSourceNamespace()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0)
End Sub
<Fact>
Public Sub TestMembers()
Dim compilation = GetTestCompilation()
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0)
TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=False, count:=0)
End Sub
<Fact>
Public Sub TestCaseInsensitivity()
Dim compilation = GetTestCompilation()
TestName(compilation, "system", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "mynamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
TestName(Compilation, "myfield", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1)
End Sub
<Fact>
Public Sub TestPartialSearch()
Dim compilation = GetTestCompilation()
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=False, includeMember:=True, count:=4)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=False, count:=4)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=True, count:=8)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=False, count:=1)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=True, count:=5)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=False, count:=5)
TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=9)
TestPredicate(compilation, Function(n) n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=2)
End Sub
Private Shared Function GetTestCompilation() As VisualBasicCompilation
Dim source As String = <text>
Namespace System
Public Class Test
End Class
End Namespace
Namespace MyNamespace
Public Class Test1
End Class
End Namespace
Public Class [MyClass]
Private myField As Integer
Friend Property MyProperty As Integer
Sub MyMethod()
End Sub
Public Event MyEvent As EventHandler
Delegate Function MyDelegate(i As Integer) As String
End Class
Structure MyStruct
End Structure
Interface MyInterface
End Interface
Enum [Enum]
EnumValue
End Enum
</text>.Value
Return CreateCompilationWithMscorlib40({source})
End Function
Private Shared Sub TestNameAndPredicate(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
TestName(compilation, name, includeNamespace, includeType, includeMember, count)
TestPredicate(compilation, Function(n) n = name, includeNamespace, includeType, includeMember, count)
End Sub
Private Shared Sub TestName(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
Dim filter = ComputeFilter(includeNamespace, includeType, includeMember)
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter))
Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count())
End Sub
Private Shared Sub TestPredicate(compilation As VisualBasicCompilation, predicate As Func(Of String, Boolean), includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer)
Dim filter = ComputeFilter(includeNamespace, includeType, includeMember)
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter))
Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count())
End Sub
Private Shared Function ComputeFilter(includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean) As SymbolFilter
Dim filter = SymbolFilter.None
filter = If(includeNamespace, filter Or SymbolFilter.Namespace, filter)
filter = If(includeType, filter Or SymbolFilter.Type, filter)
filter = If(includeMember, filter Or SymbolFilter.Member, filter)
Return filter
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor
{
internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> :
IGenerateConstructorService
where TService : AbstractGenerateConstructorService<TService, TExpressionSyntax>
where TExpressionSyntax : SyntaxNode
{
protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType);
protected abstract bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeSimpleNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeConstructorInitializerGeneration(SemanticDocument document, SyntaxNode constructorInitializer, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeSimpleAttributeNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken);
protected abstract string GenerateNameForExpression(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken);
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
protected abstract IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken);
protected abstract IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken);
protected bool WillCauseConstructorCycle(State state, SemanticDocument document, IMethodSymbol delegatedConstructor, CancellationToken cancellationToken)
{
// Check if we're in a constructor. If not, then we can always have our new constructor delegate to
// another, as it can't cause a cycle.
var currentConstructor = GetCurrentConstructor(document.SemanticModel, state.Token, cancellationToken);
if (currentConstructor == null)
return false;
// If we're delegating to the constructor we're currently in, that would cause a cycle.
if (currentConstructor.Equals(delegatedConstructor))
return true;
// Delegating to a constructor in the base type can't cause a cycle
if (!delegatedConstructor.ContainingType.Equals(currentConstructor.ContainingType))
return false;
// We need ensure that delegating constructor won't cause circular dependency.
// The chain of dependency can not exceed the number for constructors
var constructorsCount = delegatedConstructor.ContainingType.InstanceConstructors.Length;
for (var i = 0; i < constructorsCount; i++)
{
delegatedConstructor = GetDelegatedConstructor(document.SemanticModel, delegatedConstructor, cancellationToken);
if (delegatedConstructor == null)
return false;
if (delegatedConstructor.Equals(currentConstructor))
return true;
}
return true;
}
public async Task<ImmutableArray<CodeAction>> GenerateConstructorAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateConstructor, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state != null)
{
Contract.ThrowIfNull(state.TypeToGenerateIn);
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result);
// If we have any fields we'd like to generate, offer a code action to do that.
if (state.ParameterToNewFieldMap.Count > 0)
{
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0_with_fields, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: true, withProperties: false, c)));
}
// Same with a version that generates properties instead.
if (state.ParameterToNewPropertyMap.Count > 0)
{
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0_with_properties, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: true, c)));
}
// Always offer to just generate the constructor and nothing else.
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: false, c)));
return result.ToImmutable();
}
}
return ImmutableArray<CodeAction>.Empty;
}
protected static bool IsSymbolAccessible(ISymbol? symbol, SemanticDocument document)
{
if (symbol == null)
{
return false;
}
if (symbol.Kind == SymbolKind.Property)
{
if (!IsSymbolAccessible(((IPropertySymbol)symbol).SetMethod, document))
{
return false;
}
}
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
return document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
symbol.ContainingAssembly);
default:
return false;
}
}
protected string GenerateNameForArgument(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken)
{
// If it named argument then we use the name provided.
if (argument.IsNamed)
return argument.Name;
if (argument.Expression is null)
return ITypeSymbolExtensions.DefaultParameterName;
var name = this.GenerateNameForExpression(semanticModel, argument.Expression, cancellationToken);
return string.IsNullOrEmpty(name) ? ITypeSymbolExtensions.DefaultParameterName : name;
}
private ImmutableArray<ParameterName> GenerateParameterNames(
SemanticDocument document, IEnumerable<Argument> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken)
{
reservedNames ??= SpecializedCollections.EmptyList<string>();
// We can't change the names of named parameters. Any other names we're flexible on.
var isFixed = reservedNames.Select(s => true).Concat(
arguments.Select(a => a.IsNamed)).ToImmutableArray();
var parameterNames = reservedNames.Concat(
arguments.Select(a => this.GenerateNameForArgument(document.SemanticModel, a, cancellationToken))).ToImmutableArray();
var syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var comparer = syntaxFacts.StringComparer;
return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n)))
.Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule))
.Skip(reservedNames.Count).ToImmutableArray();
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor
{
internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> :
IGenerateConstructorService
where TService : AbstractGenerateConstructorService<TService, TExpressionSyntax>
where TExpressionSyntax : SyntaxNode
{
protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType);
protected abstract bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeSimpleNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeConstructorInitializerGeneration(SemanticDocument document, SyntaxNode constructorInitializer, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeSimpleAttributeNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn);
protected abstract ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken);
protected abstract string GenerateNameForExpression(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken);
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
protected abstract IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken);
protected abstract IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken);
protected bool WillCauseConstructorCycle(State state, SemanticDocument document, IMethodSymbol delegatedConstructor, CancellationToken cancellationToken)
{
// Check if we're in a constructor. If not, then we can always have our new constructor delegate to
// another, as it can't cause a cycle.
var currentConstructor = GetCurrentConstructor(document.SemanticModel, state.Token, cancellationToken);
if (currentConstructor == null)
return false;
// If we're delegating to the constructor we're currently in, that would cause a cycle.
if (currentConstructor.Equals(delegatedConstructor))
return true;
// Delegating to a constructor in the base type can't cause a cycle
if (!delegatedConstructor.ContainingType.Equals(currentConstructor.ContainingType))
return false;
// We need ensure that delegating constructor won't cause circular dependency.
// The chain of dependency can not exceed the number for constructors
var constructorsCount = delegatedConstructor.ContainingType.InstanceConstructors.Length;
for (var i = 0; i < constructorsCount; i++)
{
delegatedConstructor = GetDelegatedConstructor(document.SemanticModel, delegatedConstructor, cancellationToken);
if (delegatedConstructor == null)
return false;
if (delegatedConstructor.Equals(currentConstructor))
return true;
}
return true;
}
public async Task<ImmutableArray<CodeAction>> GenerateConstructorAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateConstructor, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state != null)
{
Contract.ThrowIfNull(state.TypeToGenerateIn);
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result);
// If we have any fields we'd like to generate, offer a code action to do that.
if (state.ParameterToNewFieldMap.Count > 0)
{
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0_with_fields, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: true, withProperties: false, c)));
}
// Same with a version that generates properties instead.
if (state.ParameterToNewPropertyMap.Count > 0)
{
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0_with_properties, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: true, c)));
}
// Always offer to just generate the constructor and nothing else.
result.Add(new MyCodeAction(
string.Format(FeaturesResources.Generate_constructor_in_0, state.TypeToGenerateIn.Name),
c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: false, c)));
return result.ToImmutable();
}
}
return ImmutableArray<CodeAction>.Empty;
}
protected static bool IsSymbolAccessible(ISymbol? symbol, SemanticDocument document)
{
if (symbol == null)
{
return false;
}
if (symbol.Kind == SymbolKind.Property)
{
if (!IsSymbolAccessible(((IPropertySymbol)symbol).SetMethod, document))
{
return false;
}
}
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
return document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
symbol.ContainingAssembly);
default:
return false;
}
}
protected string GenerateNameForArgument(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken)
{
// If it named argument then we use the name provided.
if (argument.IsNamed)
return argument.Name;
if (argument.Expression is null)
return ITypeSymbolExtensions.DefaultParameterName;
var name = this.GenerateNameForExpression(semanticModel, argument.Expression, cancellationToken);
return string.IsNullOrEmpty(name) ? ITypeSymbolExtensions.DefaultParameterName : name;
}
private ImmutableArray<ParameterName> GenerateParameterNames(
SemanticDocument document, IEnumerable<Argument> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken)
{
reservedNames ??= SpecializedCollections.EmptyList<string>();
// We can't change the names of named parameters. Any other names we're flexible on.
var isFixed = reservedNames.Select(s => true).Concat(
arguments.Select(a => a.IsNamed)).ToImmutableArray();
var parameterNames = reservedNames.Concat(
arguments.Select(a => this.GenerateNameForArgument(document.SemanticModel, a, cancellationToken))).ToImmutableArray();
var syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var comparer = syntaxFacts.StringComparer;
return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n)))
.Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule))
.Skip(reservedNames.Count).ToImmutableArray();
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/OperatorKindExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq.Expressions;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class OperatorKindExtensions
{
public static int OperatorIndex(this UnaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static UnaryOperatorKind Operator(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.OpMask;
}
public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind)
{
return kind & ~UnaryOperatorKind.Lifted;
}
public static bool IsLifted(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Lifted);
}
public static bool IsChecked(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Checked);
}
public static bool IsUserDefined(this UnaryOperatorKind kind)
{
return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined;
}
public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.Checked;
}
public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's dynamic and we're in a checked context then just mark it as checked,
// regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | UnaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.UnaryMinus:
return kind | UnaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~UnaryOperatorKind.Checked;
}
}
public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.TypeMask;
}
public static bool IsDynamic(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Dynamic;
}
public static bool IsIntegral(this UnaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte:
case UnaryOperatorKind.Byte:
case UnaryOperatorKind.Short:
case UnaryOperatorKind.UShort:
case UnaryOperatorKind.Int:
case UnaryOperatorKind.UInt:
case UnaryOperatorKind.Long:
case UnaryOperatorKind.ULong:
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
case UnaryOperatorKind.Char:
case UnaryOperatorKind.Enum:
case UnaryOperatorKind.Pointer:
return true;
}
return false;
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
Debug.Assert(type == (type & UnaryOperatorKind.TypeMask));
return kind | type;
}
public static int OperatorIndex(this BinaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static BinaryOperatorKind Operator(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.OpMask;
}
public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind)
{
return kind & ~BinaryOperatorKind.Lifted;
}
public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind)
{
return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | BinaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | BinaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | BinaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | BinaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | UnaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | UnaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | UnaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | UnaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
Debug.Assert(type == (type & BinaryOperatorKind.TypeMask));
return kind | type;
}
public static bool IsLifted(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Lifted);
}
public static bool IsDynamic(this BinaryOperatorKind kind)
{
return kind.OperandTypes() == BinaryOperatorKind.Dynamic;
}
public static bool IsComparison(this BinaryOperatorKind kind)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return true;
}
return false;
}
public static bool IsChecked(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Checked);
}
public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind)
{
if (!kind.IsChecked())
{
return false;
}
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
return true;
}
return false;
}
public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's a dynamic binop then make it checked. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | BinaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
return kind | BinaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~BinaryOperatorKind.Checked;
}
}
public static bool IsEnum(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
return true;
}
return false;
}
public static bool IsEnum(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Enum;
}
public static bool IsIntegral(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int:
case BinaryOperatorKind.UInt:
case BinaryOperatorKind.Long:
case BinaryOperatorKind.ULong:
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
case BinaryOperatorKind.Char:
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
case BinaryOperatorKind.Pointer:
case BinaryOperatorKind.PointerAndInt:
case BinaryOperatorKind.PointerAndUInt:
case BinaryOperatorKind.PointerAndLong:
case BinaryOperatorKind.PointerAndULong:
case BinaryOperatorKind.IntAndPointer:
case BinaryOperatorKind.UIntAndPointer:
case BinaryOperatorKind.LongAndPointer:
case BinaryOperatorKind.ULongAndPointer:
return true;
}
return false;
}
public static bool IsLogical(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.TypeMask;
}
public static bool IsUserDefined(this BinaryOperatorKind kind)
{
return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined;
}
public static bool IsShift(this BinaryOperatorKind kind)
{
BinaryOperatorKind type = kind.Operator();
return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift;
}
public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment)
{
if (isCompoundAssignment)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign;
case BinaryOperatorKind.Addition: return ExpressionType.AddAssign;
case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign;
case BinaryOperatorKind.Division: return ExpressionType.DivideAssign;
case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign;
case BinaryOperatorKind.And: return ExpressionType.AndAssign;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign;
case BinaryOperatorKind.Or: return ExpressionType.OrAssign;
}
}
else
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply;
case BinaryOperatorKind.Addition: return ExpressionType.Add;
case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract;
case BinaryOperatorKind.Division: return ExpressionType.Divide;
case BinaryOperatorKind.Remainder: return ExpressionType.Modulo;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShift;
case BinaryOperatorKind.Equal: return ExpressionType.Equal;
case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual;
case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan;
case BinaryOperatorKind.LessThan: return ExpressionType.LessThan;
case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual;
case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual;
case BinaryOperatorKind.And: return ExpressionType.And;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr;
case BinaryOperatorKind.Or: return ExpressionType.Or;
}
}
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
public static ExpressionType ToExpressionType(this UnaryOperatorKind kind)
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
return ExpressionType.Increment;
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PrefixDecrement:
return ExpressionType.Decrement;
case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus;
case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate;
case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not;
case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement;
case UnaryOperatorKind.True: return ExpressionType.IsTrue;
case UnaryOperatorKind.False: return ExpressionType.IsFalse;
default:
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
}
#if DEBUG
public static string Dump(this BinaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical");
if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & BinaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & BinaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
public static string Dump(this UnaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & UnaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & UnaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.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.Diagnostics;
using System.Linq.Expressions;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class OperatorKindExtensions
{
public static int OperatorIndex(this UnaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static UnaryOperatorKind Operator(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.OpMask;
}
public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind)
{
return kind & ~UnaryOperatorKind.Lifted;
}
public static bool IsLifted(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Lifted);
}
public static bool IsChecked(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Checked);
}
public static bool IsUserDefined(this UnaryOperatorKind kind)
{
return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined;
}
public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.Checked;
}
public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's dynamic and we're in a checked context then just mark it as checked,
// regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | UnaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.UnaryMinus:
return kind | UnaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~UnaryOperatorKind.Checked;
}
}
public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.TypeMask;
}
public static bool IsDynamic(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Dynamic;
}
public static bool IsIntegral(this UnaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte:
case UnaryOperatorKind.Byte:
case UnaryOperatorKind.Short:
case UnaryOperatorKind.UShort:
case UnaryOperatorKind.Int:
case UnaryOperatorKind.UInt:
case UnaryOperatorKind.Long:
case UnaryOperatorKind.ULong:
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
case UnaryOperatorKind.Char:
case UnaryOperatorKind.Enum:
case UnaryOperatorKind.Pointer:
return true;
}
return false;
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
Debug.Assert(type == (type & UnaryOperatorKind.TypeMask));
return kind | type;
}
public static int OperatorIndex(this BinaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static BinaryOperatorKind Operator(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.OpMask;
}
public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind)
{
return kind & ~BinaryOperatorKind.Lifted;
}
public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind)
{
return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | BinaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | BinaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | BinaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | BinaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | UnaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | UnaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | UnaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | UnaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
Debug.Assert(type == (type & BinaryOperatorKind.TypeMask));
return kind | type;
}
public static bool IsLifted(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Lifted);
}
public static bool IsDynamic(this BinaryOperatorKind kind)
{
return kind.OperandTypes() == BinaryOperatorKind.Dynamic;
}
public static bool IsComparison(this BinaryOperatorKind kind)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return true;
}
return false;
}
public static bool IsChecked(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Checked);
}
public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind)
{
if (!kind.IsChecked())
{
return false;
}
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
return true;
}
return false;
}
public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's a dynamic binop then make it checked. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | BinaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
return kind | BinaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~BinaryOperatorKind.Checked;
}
}
public static bool IsEnum(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
return true;
}
return false;
}
public static bool IsEnum(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Enum;
}
public static bool IsIntegral(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int:
case BinaryOperatorKind.UInt:
case BinaryOperatorKind.Long:
case BinaryOperatorKind.ULong:
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
case BinaryOperatorKind.Char:
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
case BinaryOperatorKind.Pointer:
case BinaryOperatorKind.PointerAndInt:
case BinaryOperatorKind.PointerAndUInt:
case BinaryOperatorKind.PointerAndLong:
case BinaryOperatorKind.PointerAndULong:
case BinaryOperatorKind.IntAndPointer:
case BinaryOperatorKind.UIntAndPointer:
case BinaryOperatorKind.LongAndPointer:
case BinaryOperatorKind.ULongAndPointer:
return true;
}
return false;
}
public static bool IsLogical(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.TypeMask;
}
public static bool IsUserDefined(this BinaryOperatorKind kind)
{
return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined;
}
public static bool IsShift(this BinaryOperatorKind kind)
{
BinaryOperatorKind type = kind.Operator();
return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift;
}
public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment)
{
if (isCompoundAssignment)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign;
case BinaryOperatorKind.Addition: return ExpressionType.AddAssign;
case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign;
case BinaryOperatorKind.Division: return ExpressionType.DivideAssign;
case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign;
case BinaryOperatorKind.And: return ExpressionType.AndAssign;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign;
case BinaryOperatorKind.Or: return ExpressionType.OrAssign;
}
}
else
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply;
case BinaryOperatorKind.Addition: return ExpressionType.Add;
case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract;
case BinaryOperatorKind.Division: return ExpressionType.Divide;
case BinaryOperatorKind.Remainder: return ExpressionType.Modulo;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShift;
case BinaryOperatorKind.Equal: return ExpressionType.Equal;
case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual;
case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan;
case BinaryOperatorKind.LessThan: return ExpressionType.LessThan;
case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual;
case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual;
case BinaryOperatorKind.And: return ExpressionType.And;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr;
case BinaryOperatorKind.Or: return ExpressionType.Or;
}
}
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
public static ExpressionType ToExpressionType(this UnaryOperatorKind kind)
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
return ExpressionType.Increment;
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PrefixDecrement:
return ExpressionType.Decrement;
case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus;
case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate;
case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not;
case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement;
case UnaryOperatorKind.True: return ExpressionType.IsTrue;
case UnaryOperatorKind.False: return ExpressionType.IsFalse;
default:
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
}
#if DEBUG
public static string Dump(this BinaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical");
if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & BinaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & BinaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
public static string Dump(this UnaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & UnaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & UnaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasicTest/Structure/MultilineLambdaStructureTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class MultilineLambdaStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of MultiLineLambdaExpressionSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New MultilineLambdaStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInClassScope() As Task
Const code = "
Class C
Dim r = {|span:$$Sub()
End Sub|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Sub() ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInMethodScope() As Task
Const code = "
Class C
Sub M()
Dim r = {|span:$$Sub()
End Sub|}
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Sub() ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestFunction() As Task
Const code = "
Class C
Dim r = {|span:$$Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer))
End Function|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInArgumentContext() As Task
Const code = "
Class C
Sub M()
MethodCall({|span:$$Function(x As Integer, y As List(Of String)) As List(Of List(Of String))
Return Nothing
End Function|})
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestLambdaWithReturnType() As Task
Const code = "
Class C
Sub M()
Dim f = {|span:$$Function(x) As Integer
Return x
End Function|}
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x) As Integer ...", autoCollapse:=False))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class MultilineLambdaStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of MultiLineLambdaExpressionSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New MultilineLambdaStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInClassScope() As Task
Const code = "
Class C
Dim r = {|span:$$Sub()
End Sub|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Sub() ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInMethodScope() As Task
Const code = "
Class C
Sub M()
Dim r = {|span:$$Sub()
End Sub|}
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Sub() ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestFunction() As Task
Const code = "
Class C
Dim r = {|span:$$Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer))
End Function|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestInArgumentContext() As Task
Const code = "
Class C
Sub M()
MethodCall({|span:$$Function(x As Integer, y As List(Of String)) As List(Of List(Of String))
Return Nothing
End Function|})
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) ...", autoCollapse:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestLambdaWithReturnType() As Task
Const code = "
Class C
Sub M()
Dim f = {|span:$$Function(x) As Integer
Return x
End Function|}
End Sub
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Function(x) As Integer ...", autoCollapse:=False))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.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.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
<Guid("782CB503-84B1-4b8f-9AAD-A12B75905015"), ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Friend Interface IVbCompilerHost
''' <summary>
''' Output a string to the standard output (console, file, pane, etc.)
''' </summary>
Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String)
''' <summary>
''' Returns the system SDK directory, where mscorlib.dll and Microsoft.VisualBasic.dll is
''' located.
''' </summary>
<PreserveSig>
Function GetSdkPath(<MarshalAs(UnmanagedType.BStr), Out> ByRef sdkPath As String) As Integer
''' <summary>
''' Get the target library type.
''' </summary>
Function GetTargetLibraryType() As VBTargetLibraryType
End Interface
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.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
<Guid("782CB503-84B1-4b8f-9AAD-A12B75905015"), ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Friend Interface IVbCompilerHost
''' <summary>
''' Output a string to the standard output (console, file, pane, etc.)
''' </summary>
Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String)
''' <summary>
''' Returns the system SDK directory, where mscorlib.dll and Microsoft.VisualBasic.dll is
''' located.
''' </summary>
<PreserveSig>
Function GetSdkPath(<MarshalAs(UnmanagedType.BStr), Out> ByRef sdkPath As String) As Integer
''' <summary>
''' Get the target library type.
''' </summary>
Function GetTargetLibraryType() As VBTargetLibraryType
End Interface
End Namespace
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/Core/Analyzers/RemoveUnnecessaryCast/AbstractRemoveUnnecessaryCastDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast
{
internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer<
TLanguageKindEnum,
TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TLanguageKindEnum : struct
where TCastExpression : SyntaxNode
{
protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId,
EnforceOnBuildValues.RemoveUnnecessaryCast,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)),
isUnnecessary: true)
{
}
protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; }
protected abstract TextSpan GetFadeSpan(TCastExpression node);
protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest);
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var diagnostic = TryRemoveCastExpression(
context.SemanticModel,
(TCastExpression)context.Node,
context.CancellationToken);
if (diagnostic != null)
{
context.ReportDiagnostic(diagnostic);
}
}
private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!IsUnnecessaryCast(model, node, cancellationToken))
{
return null;
}
var tree = model.SyntaxTree;
if (tree.OverlapsHiddenPosition(node.Span, cancellationToken))
{
return null;
}
return Diagnostic.Create(
Descriptor,
node.SyntaxTree.GetLocation(GetFadeSpan(node)),
ImmutableArray.Create(node.GetLocation()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast
{
internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer<
TLanguageKindEnum,
TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TLanguageKindEnum : struct
where TCastExpression : SyntaxNode
{
protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId,
EnforceOnBuildValues.RemoveUnnecessaryCast,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)),
isUnnecessary: true)
{
}
protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; }
protected abstract TextSpan GetFadeSpan(TCastExpression node);
protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest);
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var diagnostic = TryRemoveCastExpression(
context.SemanticModel,
(TCastExpression)context.Node,
context.CancellationToken);
if (diagnostic != null)
{
context.ReportDiagnostic(diagnostic);
}
}
private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!IsUnnecessaryCast(model, node, cancellationToken))
{
return null;
}
var tree = model.SyntaxTree;
if (tree.OverlapsHiddenPosition(node.Span, cancellationToken))
{
return null;
}
return Diagnostic.Create(
Descriptor,
node.SyntaxTree.GetLocation(GetFadeSpan(node)),
ImmutableArray.Create(node.GetLocation()));
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/EditorConfigNamingStyleParserTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.EditorConfigNamingStyleParser;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles
{
public class EditorConfigNamingStyleParserTests
{
[Fact]
public static void TestPascalCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "method_and_property_symbols",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "pascal_case_style",
["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property",
["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*",
["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case"
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
Assert.Equal("method_and_property_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Property)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Empty(symbolSpec.RequiredModifierList);
var expectedApplicableAccessibilityList = new[]
{
Accessibility.NotApplicable,
Accessibility.Public,
Accessibility.Internal,
Accessibility.Private,
Accessibility.Protected,
Accessibility.ProtectedAndInternal,
Accessibility.ProtectedOrInternal
};
AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList);
Assert.Equal("pascal_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
[WorkItem(40705, "https://github.com/dotnet/roslyn/issues/40705")]
public static void TestPascalCaseRuleWithKeyCapitalization()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "Method_and_Property_symbols",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "Pascal_Case_style",
["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property",
["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*",
["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case"
};
var result = ParseDictionary(dictionary);
var namingRule = Assert.Single(result.NamingRules);
var namingStyle = Assert.Single(result.NamingStyles);
var symbolSpec = Assert.Single(result.SymbolSpecifications);
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
}
[Fact]
public static void TestAsyncMethodsAndLocalFunctionsRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "error",
["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "method_symbols",
["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async_style",
["dotnet_naming_symbols.method_symbols.applicable_kinds"] = "method,local_function",
["dotnet_naming_symbols.method_symbols.required_modifiers"] = "async",
["dotnet_naming_style.end_in_async_style.capitalization "] = "pascal_case",
["dotnet_naming_style.end_in_async_style.required_suffix"] = "Async",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Error, namingRule.EnforcementLevel);
Assert.Equal("method_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(MethodKind.LocalFunction)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Single(symbolSpec.RequiredModifierList);
Assert.Contains(new ModifierKind(ModifierKindEnum.IsAsync), symbolSpec.RequiredModifierList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Equal("end_in_async_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("Async", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestRuleWithoutCapitalization()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "any_async_methods",
["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async",
["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "suggestion",
["dotnet_naming_symbols.any_async_methods.applicable_kinds"] = "method",
["dotnet_naming_symbols.any_async_methods.applicable_accessibilities"] = "*",
["dotnet_naming_symbols.any_async_methods.required_modifiers"] = "async",
["dotnet_naming_style.end_in_async.required_suffix"] = "Async",
};
var result = ParseDictionary(dictionary);
Assert.Empty(result.NamingStyles);
}
[Fact]
public static void TestPublicMembersCapitalizedRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.public_members_must_be_capitalized.severity"] = "suggestion",
["dotnet_naming_rule.public_members_must_be_capitalized.symbols"] = "public_symbols",
["dotnet_naming_rule.public_members_must_be_capitalized.style"] = "first_word_upper_case_style",
["dotnet_naming_symbols.public_symbols.applicable_kinds"] = "property,method,field,event,delegate",
["dotnet_naming_symbols.public_symbols.applicable_accessibilities"] = "public,internal,protected,protected_internal",
["dotnet_naming_style.first_word_upper_case_style.capitalization"] = "first_word_upper",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("public_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(TypeKind.Delegate)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
var expectedApplicableAccessibilityList = new[]
{
Accessibility.Public,
Accessibility.Internal,
Accessibility.Protected,
Accessibility.ProtectedOrInternal
};
AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("first_word_upper_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.FirstUpper, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestNonPublicMembersLowerCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.non_public_members_must_be_lower_case.severity"] = "incorrect",
["dotnet_naming_rule.non_public_members_must_be_lower_case.symbols "] = "non_public_symbols",
["dotnet_naming_rule.non_public_members_must_be_lower_case.style "] = "all_lower_case_style",
["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate",
["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private",
["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Hidden, namingRule.EnforcementLevel);
Assert.Equal("non_public_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(TypeKind.Delegate)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Single(symbolSpec.ApplicableAccessibilityList);
Assert.Contains(Accessibility.Private, symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("all_lower_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.AllLower, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestParametersAndLocalsAreCamelCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.parameters_and_locals_are_camel_case.severity"] = "suggestion",
["dotnet_naming_rule.parameters_and_locals_are_camel_case.symbols"] = "parameters_and_locals",
["dotnet_naming_rule.parameters_and_locals_are_camel_case.style"] = "camel_case_style",
["dotnet_naming_symbols.parameters_and_locals.applicable_kinds"] = "parameter,local",
["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("parameters_and_locals", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.Local),
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("camel_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestLocalFunctionsAreCamelCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.local_functions_are_camel_case.severity"] = "suggestion",
["dotnet_naming_rule.local_functions_are_camel_case.symbols"] = "local_functions",
["dotnet_naming_rule.local_functions_are_camel_case.style"] = "camel_case_style",
["dotnet_naming_symbols.local_functions.applicable_kinds"] = "local_function",
["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("local_functions", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.LocalFunction) };
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("camel_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestNoRulesAreReturned()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate",
["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private",
["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower",
};
var result = ParseDictionary(dictionary);
Assert.Empty(result.NamingRules);
Assert.Empty(result.NamingStyles);
Assert.Empty(result.SymbolSpecifications);
}
[Theory]
[InlineData("property,method", new object[] { SymbolKind.Property, MethodKind.Ordinary })]
[InlineData("namespace", new object[] { SymbolKind.Namespace })]
[InlineData("type_parameter", new object[] { SymbolKind.TypeParameter })]
[InlineData("interface", new object[] { TypeKind.Interface })]
[InlineData("*", new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })]
[InlineData(null, new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })]
[InlineData("property,method,invalid", new object[] { SymbolKind.Property, MethodKind.Ordinary })]
[InlineData("invalid", new object[] { })]
[InlineData("", new object[] { })]
[WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")]
public static void TestApplicableKindsParse(string specification, object[] typeOrSymbolKinds)
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_rule.kinds_parse.severity"] = "error",
["dotnet_naming_rule.kinds_parse.symbols"] = "kinds",
["dotnet_naming_rule.kinds_parse.style"] = "pascal_case",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
if (specification != null)
{
rule["dotnet_naming_symbols.kinds.applicable_kinds"] = specification;
}
var kinds = typeOrSymbolKinds.Select(NamingStylesTestOptionSets.ToSymbolKindOrTypeKind).ToArray();
var result = ParseDictionary(rule);
Assert.Equal(kinds, result.SymbolSpecifications.SelectMany(x => x.ApplicableSymbolKindList));
}
[Theory]
[InlineData("internal,protected_internal", new[] { Accessibility.Internal, Accessibility.ProtectedOrInternal })]
[InlineData("friend,protected_friend", new[] { Accessibility.Friend, Accessibility.ProtectedOrFriend })]
[InlineData("private_protected", new[] { Accessibility.ProtectedAndInternal })]
[InlineData("local", new[] { Accessibility.NotApplicable })]
[InlineData("*", new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })]
[InlineData(null, new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })]
[InlineData("internal,protected,invalid", new[] { Accessibility.Internal, Accessibility.Protected })]
[InlineData("invalid", new Accessibility[] { })]
[InlineData("", new Accessibility[] { })]
[WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")]
public static void TestApplicableAccessibilitiesParse(string specification, Accessibility[] accessibilities)
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_rule.accessibilities_parse.severity"] = "error",
["dotnet_naming_rule.accessibilities_parse.symbols"] = "accessibilities",
["dotnet_naming_rule.accessibilities_parse.style"] = "pascal_case",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
if (specification != null)
{
rule["dotnet_naming_symbols.accessibilities.applicable_accessibilities"] = specification;
}
var result = ParseDictionary(rule);
Assert.Equal(accessibilities, result.SymbolSpecifications.SelectMany(x => x.ApplicableAccessibilityList));
}
[Fact]
public static void TestRequiredModifiersParse()
{
var charpRule = new Dictionary<string, string>()
{
["dotnet_naming_rule.modifiers_parse.severity"] = "error",
["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers",
["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case",
["dotnet_naming_symbols.modifiers.required_modifiers"] = "abstract,static",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
var vbRule = new Dictionary<string, string>()
{
["dotnet_naming_rule.modifiers_parse.severity"] = "error",
["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers",
["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case",
["dotnet_naming_symbols.modifiers.required_modifiers"] = "must_inherit,shared",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
var csharpResult = ParseDictionary(charpRule);
var vbResult = ParseDictionary(vbRule);
Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)),
vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)));
Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)),
vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)));
}
[Fact]
[WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")]
public static void TestPrefixParse()
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_style.pascal_case_and_prefix_style.required_prefix"] = "I",
["dotnet_naming_style.pascal_case_and_prefix_style.capitalization"] = "pascal_case",
["dotnet_naming_symbols.symbols.applicable_kinds"] = "interface",
["dotnet_naming_symbols.symbols.applicable_accessibilities"] = "*",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.symbols"] = "symbols",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.style"] = "pascal_case_and_prefix_style",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.severity"] = "warning",
};
var result = ParseDictionary(rule);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
Assert.Equal("symbols", symbolSpec.Name);
var expectedApplicableTypeKindList = new[] { new SymbolKindOrTypeKind(TypeKind.Interface) };
AssertEx.SetEqual(expectedApplicableTypeKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal("pascal_case_and_prefix_style", namingStyle.Name);
Assert.Equal("I", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestEditorConfigParseForApplicableSymbolKinds()
{
var symbolSpecifications = CreateDefaultSymbolSpecification();
foreach (var applicableSymbolKind in symbolSpecifications.ApplicableSymbolKindList)
{
var editorConfigString = EditorConfigNamingStyleParser.ToEditorConfigString(ImmutableArray.Create(applicableSymbolKind));
Assert.True(!string.IsNullOrEmpty(editorConfigString));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.EditorConfigNamingStyleParser;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles
{
public class EditorConfigNamingStyleParserTests
{
[Fact]
public static void TestPascalCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "method_and_property_symbols",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "pascal_case_style",
["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property",
["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*",
["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case"
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
Assert.Equal("method_and_property_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Property)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Empty(symbolSpec.RequiredModifierList);
var expectedApplicableAccessibilityList = new[]
{
Accessibility.NotApplicable,
Accessibility.Public,
Accessibility.Internal,
Accessibility.Private,
Accessibility.Protected,
Accessibility.ProtectedAndInternal,
Accessibility.ProtectedOrInternal
};
AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList);
Assert.Equal("pascal_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
[WorkItem(40705, "https://github.com/dotnet/roslyn/issues/40705")]
public static void TestPascalCaseRuleWithKeyCapitalization()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "Method_and_Property_symbols",
["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "Pascal_Case_style",
["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property",
["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*",
["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case"
};
var result = ParseDictionary(dictionary);
var namingRule = Assert.Single(result.NamingRules);
var namingStyle = Assert.Single(result.NamingStyles);
var symbolSpec = Assert.Single(result.SymbolSpecifications);
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
}
[Fact]
public static void TestAsyncMethodsAndLocalFunctionsRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "error",
["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "method_symbols",
["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async_style",
["dotnet_naming_symbols.method_symbols.applicable_kinds"] = "method,local_function",
["dotnet_naming_symbols.method_symbols.required_modifiers"] = "async",
["dotnet_naming_style.end_in_async_style.capitalization "] = "pascal_case",
["dotnet_naming_style.end_in_async_style.required_suffix"] = "Async",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Error, namingRule.EnforcementLevel);
Assert.Equal("method_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(MethodKind.LocalFunction)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Single(symbolSpec.RequiredModifierList);
Assert.Contains(new ModifierKind(ModifierKindEnum.IsAsync), symbolSpec.RequiredModifierList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Equal("end_in_async_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("Async", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestRuleWithoutCapitalization()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "any_async_methods",
["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async",
["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "suggestion",
["dotnet_naming_symbols.any_async_methods.applicable_kinds"] = "method",
["dotnet_naming_symbols.any_async_methods.applicable_accessibilities"] = "*",
["dotnet_naming_symbols.any_async_methods.required_modifiers"] = "async",
["dotnet_naming_style.end_in_async.required_suffix"] = "Async",
};
var result = ParseDictionary(dictionary);
Assert.Empty(result.NamingStyles);
}
[Fact]
public static void TestPublicMembersCapitalizedRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.public_members_must_be_capitalized.severity"] = "suggestion",
["dotnet_naming_rule.public_members_must_be_capitalized.symbols"] = "public_symbols",
["dotnet_naming_rule.public_members_must_be_capitalized.style"] = "first_word_upper_case_style",
["dotnet_naming_symbols.public_symbols.applicable_kinds"] = "property,method,field,event,delegate",
["dotnet_naming_symbols.public_symbols.applicable_accessibilities"] = "public,internal,protected,protected_internal",
["dotnet_naming_style.first_word_upper_case_style.capitalization"] = "first_word_upper",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("public_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(TypeKind.Delegate)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
var expectedApplicableAccessibilityList = new[]
{
Accessibility.Public,
Accessibility.Internal,
Accessibility.Protected,
Accessibility.ProtectedOrInternal
};
AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("first_word_upper_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.FirstUpper, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestNonPublicMembersLowerCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.non_public_members_must_be_lower_case.severity"] = "incorrect",
["dotnet_naming_rule.non_public_members_must_be_lower_case.symbols "] = "non_public_symbols",
["dotnet_naming_rule.non_public_members_must_be_lower_case.style "] = "all_lower_case_style",
["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate",
["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private",
["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Hidden, namingRule.EnforcementLevel);
Assert.Equal("non_public_symbols", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(TypeKind.Delegate)
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Single(symbolSpec.ApplicableAccessibilityList);
Assert.Contains(Accessibility.Private, symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("all_lower_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.AllLower, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestParametersAndLocalsAreCamelCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.parameters_and_locals_are_camel_case.severity"] = "suggestion",
["dotnet_naming_rule.parameters_and_locals_are_camel_case.symbols"] = "parameters_and_locals",
["dotnet_naming_rule.parameters_and_locals_are_camel_case.style"] = "camel_case_style",
["dotnet_naming_symbols.parameters_and_locals.applicable_kinds"] = "parameter,local",
["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("parameters_and_locals", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[]
{
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.Local),
};
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("camel_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestLocalFunctionsAreCamelCaseRule()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_rule.local_functions_are_camel_case.severity"] = "suggestion",
["dotnet_naming_rule.local_functions_are_camel_case.symbols"] = "local_functions",
["dotnet_naming_rule.local_functions_are_camel_case.style"] = "camel_case_style",
["dotnet_naming_symbols.local_functions.applicable_kinds"] = "local_function",
["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case",
};
var result = ParseDictionary(dictionary);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel);
Assert.Equal("local_functions", symbolSpec.Name);
var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.LocalFunction) };
AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal(
new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal },
symbolSpec.ApplicableAccessibilityList);
Assert.Empty(symbolSpec.RequiredModifierList);
Assert.Equal("camel_case_style", namingStyle.Name);
Assert.Equal("", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestNoRulesAreReturned()
{
var dictionary = new Dictionary<string, string>()
{
["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate",
["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private",
["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower",
};
var result = ParseDictionary(dictionary);
Assert.Empty(result.NamingRules);
Assert.Empty(result.NamingStyles);
Assert.Empty(result.SymbolSpecifications);
}
[Theory]
[InlineData("property,method", new object[] { SymbolKind.Property, MethodKind.Ordinary })]
[InlineData("namespace", new object[] { SymbolKind.Namespace })]
[InlineData("type_parameter", new object[] { SymbolKind.TypeParameter })]
[InlineData("interface", new object[] { TypeKind.Interface })]
[InlineData("*", new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })]
[InlineData(null, new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })]
[InlineData("property,method,invalid", new object[] { SymbolKind.Property, MethodKind.Ordinary })]
[InlineData("invalid", new object[] { })]
[InlineData("", new object[] { })]
[WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")]
public static void TestApplicableKindsParse(string specification, object[] typeOrSymbolKinds)
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_rule.kinds_parse.severity"] = "error",
["dotnet_naming_rule.kinds_parse.symbols"] = "kinds",
["dotnet_naming_rule.kinds_parse.style"] = "pascal_case",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
if (specification != null)
{
rule["dotnet_naming_symbols.kinds.applicable_kinds"] = specification;
}
var kinds = typeOrSymbolKinds.Select(NamingStylesTestOptionSets.ToSymbolKindOrTypeKind).ToArray();
var result = ParseDictionary(rule);
Assert.Equal(kinds, result.SymbolSpecifications.SelectMany(x => x.ApplicableSymbolKindList));
}
[Theory]
[InlineData("internal,protected_internal", new[] { Accessibility.Internal, Accessibility.ProtectedOrInternal })]
[InlineData("friend,protected_friend", new[] { Accessibility.Friend, Accessibility.ProtectedOrFriend })]
[InlineData("private_protected", new[] { Accessibility.ProtectedAndInternal })]
[InlineData("local", new[] { Accessibility.NotApplicable })]
[InlineData("*", new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })]
[InlineData(null, new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })]
[InlineData("internal,protected,invalid", new[] { Accessibility.Internal, Accessibility.Protected })]
[InlineData("invalid", new Accessibility[] { })]
[InlineData("", new Accessibility[] { })]
[WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")]
public static void TestApplicableAccessibilitiesParse(string specification, Accessibility[] accessibilities)
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_rule.accessibilities_parse.severity"] = "error",
["dotnet_naming_rule.accessibilities_parse.symbols"] = "accessibilities",
["dotnet_naming_rule.accessibilities_parse.style"] = "pascal_case",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
if (specification != null)
{
rule["dotnet_naming_symbols.accessibilities.applicable_accessibilities"] = specification;
}
var result = ParseDictionary(rule);
Assert.Equal(accessibilities, result.SymbolSpecifications.SelectMany(x => x.ApplicableAccessibilityList));
}
[Fact]
public static void TestRequiredModifiersParse()
{
var charpRule = new Dictionary<string, string>()
{
["dotnet_naming_rule.modifiers_parse.severity"] = "error",
["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers",
["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case",
["dotnet_naming_symbols.modifiers.required_modifiers"] = "abstract,static",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
var vbRule = new Dictionary<string, string>()
{
["dotnet_naming_rule.modifiers_parse.severity"] = "error",
["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers",
["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case",
["dotnet_naming_symbols.modifiers.required_modifiers"] = "must_inherit,shared",
["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case",
};
var csharpResult = ParseDictionary(charpRule);
var vbResult = ParseDictionary(vbRule);
Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)),
vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)));
Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)),
vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)));
}
[Fact]
[WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")]
public static void TestPrefixParse()
{
var rule = new Dictionary<string, string>()
{
["dotnet_naming_style.pascal_case_and_prefix_style.required_prefix"] = "I",
["dotnet_naming_style.pascal_case_and_prefix_style.capitalization"] = "pascal_case",
["dotnet_naming_symbols.symbols.applicable_kinds"] = "interface",
["dotnet_naming_symbols.symbols.applicable_accessibilities"] = "*",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.symbols"] = "symbols",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.style"] = "pascal_case_and_prefix_style",
["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.severity"] = "warning",
};
var result = ParseDictionary(rule);
Assert.Single(result.NamingRules);
var namingRule = result.NamingRules.Single();
Assert.Single(result.NamingStyles);
var namingStyle = result.NamingStyles.Single();
Assert.Single(result.SymbolSpecifications);
var symbolSpec = result.SymbolSpecifications.Single();
Assert.Equal(namingStyle.ID, namingRule.NamingStyleID);
Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID);
Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel);
Assert.Equal("symbols", symbolSpec.Name);
var expectedApplicableTypeKindList = new[] { new SymbolKindOrTypeKind(TypeKind.Interface) };
AssertEx.SetEqual(expectedApplicableTypeKindList, symbolSpec.ApplicableSymbolKindList);
Assert.Equal("pascal_case_and_prefix_style", namingStyle.Name);
Assert.Equal("I", namingStyle.Prefix);
Assert.Equal("", namingStyle.Suffix);
Assert.Equal("", namingStyle.WordSeparator);
Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme);
}
[Fact]
public static void TestEditorConfigParseForApplicableSymbolKinds()
{
var symbolSpecifications = CreateDefaultSymbolSpecification();
foreach (var applicableSymbolKind in symbolSpecifications.ApplicableSymbolKindList)
{
var editorConfigString = EditorConfigNamingStyleParser.ToEditorConfigString(ImmutableArray.Create(applicableSymbolKind));
Assert.True(!string.IsNullOrEmpty(editorConfigString));
}
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Syntax/Syntax.xsd | <?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="define-parse-tree">
<xs:complexType>
<xs:sequence>
<xs:element name="definitions">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element maxOccurs="unbounded" name="node-structure">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="description" type="xs:string" />
<xs:element maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="spec-section" type="xs:string" />
<xs:element maxOccurs="unbounded" name="grammar" type="xs:string" />
<xs:element maxOccurs="unbounded" name="node-kind">
<xs:complexType mixed="true">
<xs:sequence minOccurs="0">
<xs:element minOccurs="0" name="description" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="token-text" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="child">
<xs:complexType mixed="true">
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="kind">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="node-kind" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="kind" type="xs:string" use="optional" />
<xs:attribute name="optional" type="xs:boolean" use="optional" />
<xs:attribute name="list" type="xs:boolean" use="optional" />
<xs:attribute name="separator-kind" type="xs:string" use="optional" />
<xs:attribute name="separator-name" type="xs:string" use="optional" />
<xs:attribute name="min-count" type="xs:unsignedByte" use="optional" />
<xs:attribute name="order" type="xs:byte" use="optional" />
<xs:attribute name="optional-elements" type="xs:boolean" use="optional" />
<xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
<xs:element name="field">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" name="lm-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" name="native-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="abstract" type="xs:boolean" use="optional" />
<xs:attribute name="partial" type="xs:boolean" use="optional" />
<xs:attribute name="predefined" type="xs:boolean" use="optional" />
<xs:attribute name="root" type="xs:boolean" use="optional" />
<xs:attribute name="parent" type="xs:string" use="optional" />
<xs:attribute name="token-root" type="xs:boolean" use="optional" />
<xs:attribute name="default-trailing-trivia" type="xs:string" use="optional" />
<xs:attribute name="has-default-factory" type="xs:boolean" use="optional" />
<xs:attribute name="no-factory" type="xs:boolean" use="optional" />
<xs:attribute name="trivia-root" type="xs:boolean" use="optional" />
<xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="node-kind-alias">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="alias" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="enumeration">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" name="lm-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="enumerators">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="enumerator">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="namespace" type="xs:string" use="required" />
<xs:attribute name="visitor" type="xs:string" use="required" />
<xs:attribute name="rewrite-visitor" type="xs:string" use="required" />
<xs:attribute name="factory-class" type="xs:string" use="required" />
<xs:attribute name="contextual-factory-class" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>
| <?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="define-parse-tree">
<xs:complexType>
<xs:sequence>
<xs:element name="definitions">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element maxOccurs="unbounded" name="node-structure">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="description" type="xs:string" />
<xs:element maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="spec-section" type="xs:string" />
<xs:element maxOccurs="unbounded" name="grammar" type="xs:string" />
<xs:element maxOccurs="unbounded" name="node-kind">
<xs:complexType mixed="true">
<xs:sequence minOccurs="0">
<xs:element minOccurs="0" name="description" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="token-text" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="child">
<xs:complexType mixed="true">
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" maxOccurs="unbounded" name="kind">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="node-kind" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="kind" type="xs:string" use="optional" />
<xs:attribute name="optional" type="xs:boolean" use="optional" />
<xs:attribute name="list" type="xs:boolean" use="optional" />
<xs:attribute name="separator-kind" type="xs:string" use="optional" />
<xs:attribute name="separator-name" type="xs:string" use="optional" />
<xs:attribute name="min-count" type="xs:unsignedByte" use="optional" />
<xs:attribute name="order" type="xs:byte" use="optional" />
<xs:attribute name="optional-elements" type="xs:boolean" use="optional" />
<xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
<xs:element name="field">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" name="lm-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" name="native-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="abstract" type="xs:boolean" use="optional" />
<xs:attribute name="partial" type="xs:boolean" use="optional" />
<xs:attribute name="predefined" type="xs:boolean" use="optional" />
<xs:attribute name="root" type="xs:boolean" use="optional" />
<xs:attribute name="parent" type="xs:string" use="optional" />
<xs:attribute name="token-root" type="xs:boolean" use="optional" />
<xs:attribute name="default-trailing-trivia" type="xs:string" use="optional" />
<xs:attribute name="has-default-factory" type="xs:boolean" use="optional" />
<xs:attribute name="no-factory" type="xs:boolean" use="optional" />
<xs:attribute name="trivia-root" type="xs:boolean" use="optional" />
<xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="node-kind-alias">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="alias" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="enumeration">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" />
<xs:element minOccurs="0" name="lm-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element maxOccurs="unbounded" name="native-equiv">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="enumerators">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="enumerator">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:element name="description" type="xs:string" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="namespace" type="xs:string" use="required" />
<xs:attribute name="visitor" type="xs:string" use="required" />
<xs:attribute name="rewrite-visitor" type="xs:string" use="required" />
<xs:attribute name="factory-class" type="xs:string" use="required" />
<xs:attribute name="contextual-factory-class" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/CommandHandlers/ExecuteInInteractiveCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Implements a execute in interactive command handler.
/// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/>
/// in order to ensure that the interactive command can be exposed without the necessity
/// to load any of the interactive dll files just to get the command's status.
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name("Interactive Command Handler")]
internal class ExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers;
public string DisplayName => EditorFeaturesResources.Execute_In_Interactive;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExecuteInInteractiveCommandHandler(
[ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers)
{
_executeInInteractiveHandlers = executeInInteractiveHandlers;
}
private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer)
{
return _executeInInteractiveHandlers
.Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType))
.SingleOrDefault();
}
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
=> GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false;
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
{
return GetCommandHandler(args.SubjectBuffer) == null
? CommandState.Unavailable
: CommandState.Available;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Implements a execute in interactive command handler.
/// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/>
/// in order to ensure that the interactive command can be exposed without the necessity
/// to load any of the interactive dll files just to get the command's status.
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name("Interactive Command Handler")]
internal class ExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers;
public string DisplayName => EditorFeaturesResources.Execute_In_Interactive;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExecuteInInteractiveCommandHandler(
[ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers)
{
_executeInInteractiveHandlers = executeInInteractiveHandlers;
}
private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer)
{
return _executeInInteractiveHandlers
.Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType))
.SingleOrDefault();
}
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
=> GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false;
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
{
return GetCommandHandler(args.SubjectBuffer) == null
? CommandState.Unavailable
: CommandState.Available;
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Emit/EmitOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers
{
internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider
{
private class State
{
public TextSpan TextSpan { get; private set; }
public IMethodSymbol? MatchingConstructor { get; private set; }
public IMethodSymbol? DelegatedConstructor { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public ImmutableArray<ISymbol> SelectedMembers { get; private set; }
public ImmutableArray<IParameterSymbol> Parameters { get; private set; }
public bool IsContainedInUnsafeType { get; private set; }
public static async Task<State?> TryGenerateAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty))
{
return false;
}
SelectedMembers = selectedMembers;
ContainingType = containingType;
TextSpan = textSpan;
if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface)
{
return false;
}
IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType);
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
Parameters = DetermineParameters(selectedMembers, rules);
MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters);
// We are going to create a new contructor and pass part of the parameters into DelegatedConstructor,
// so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated.
DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters);
return true;
}
private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes(
INamedTypeSymbol containingType,
ImmutableArray<IParameterSymbol> parameters)
{
var q =
from c in containingType.InstanceConstructors
orderby c.Parameters.Length descending
where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length
where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
let constructorTypes = c.Parameters.Select(p => p.Type)
let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default)
select c;
return q.FirstOrDefault();
}
private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters)
=> containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters));
private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters)
=> parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.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 System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers
{
internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider
{
private class State
{
public TextSpan TextSpan { get; private set; }
public IMethodSymbol? MatchingConstructor { get; private set; }
public IMethodSymbol? DelegatedConstructor { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public ImmutableArray<ISymbol> SelectedMembers { get; private set; }
public ImmutableArray<IParameterSymbol> Parameters { get; private set; }
public bool IsContainedInUnsafeType { get; private set; }
public static async Task<State?> TryGenerateAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
AbstractGenerateConstructorFromMembersCodeRefactoringProvider service,
Document document,
TextSpan textSpan,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
CancellationToken cancellationToken)
{
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty))
{
return false;
}
SelectedMembers = selectedMembers;
ContainingType = containingType;
TextSpan = textSpan;
if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface)
{
return false;
}
IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType);
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
Parameters = DetermineParameters(selectedMembers, rules);
MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters);
// We are going to create a new contructor and pass part of the parameters into DelegatedConstructor,
// so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated.
DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters);
return true;
}
private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes(
INamedTypeSymbol containingType,
ImmutableArray<IParameterSymbol> parameters)
{
var q =
from c in containingType.InstanceConstructors
orderby c.Parameters.Length descending
where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length
where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
let constructorTypes = c.Parameters.Select(p => p.Type)
let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default)
select c;
return q.FirstOrDefault();
}
private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters)
=> containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters));
private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters)
=> parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type));
}
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CommandHandlers;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.GoToImplementation
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.GoToImplementation)]
internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToImplementationCommandHandler(
IThreadingContext threadingContext,
IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter)
{
}
public override string DisplayName => EditorFeaturesResources.Go_To_Implementation;
protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations;
protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation;
protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken)
=> service.FindImplementationsAsync(document, caretPosition, context, cancellationToken);
protected override IFindUsagesService? GetService(Document? document)
=> document?.GetLanguageService<IFindUsagesService>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CommandHandlers;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.GoToImplementation
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.GoToImplementation)]
internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToImplementationCommandHandler(
IThreadingContext threadingContext,
IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter)
{
}
public override string DisplayName => EditorFeaturesResources.Go_To_Implementation;
protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations;
protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation;
protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken)
=> service.FindImplementationsAsync(document, caretPosition, context, cancellationToken);
protected override IFindUsagesService? GetService(Document? document)
=> document?.GetLanguageService<IFindUsagesService>();
}
}
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/vbc/App.config | <?xml version="1.0" encoding="utf-8" ?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<runtime>
<AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" />
<gcServer enabled="true" />
<gcConcurrent enabled="false"/>
</runtime>
</configuration>
| <?xml version="1.0" encoding="utf-8" ?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<runtime>
<AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" />
<gcServer enabled="true" />
<gcConcurrent enabled="false"/>
</runtime>
</configuration>
| -1 |
dotnet/roslyn | 55,020 | Fix 'move type' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:05:46Z | 2021-07-22T18:42:39Z | f6c6a6f407383d6bc74f5399f840261a8503951c | 91d692fd452933d9852186bdcd5a911b3f2c455b | Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/MDTestAttributeApplicationLib.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L N ! ^5 @ @ @ 5 W @ ` H .text d `.rsrc @ @ @.reloc ` @ B @5 H H (
*0 {
+ * "} * * 0
+ * (
*(
*(
*(
*(
*BSJB v4.0.30319 l #~ T #Strings $ #US , #GUID < #Blob W %3
B < |